Shift 2D Grid - Problem
Given a 2D grid of size m x n and an integer k, you need to shift the grid k times.
In one shift operation:
- Element at
grid[i][j]moves togrid[i][j + 1] - Element at
grid[i][n - 1]moves togrid[i + 1][0] - Element at
grid[m - 1][n - 1]moves togrid[0][0]
Return the 2D grid after applying shift operation k times.
Input & Output
Example 1 — Basic Shift
$
Input:
grid = [[1,2,3],[4,5,6]], k = 1
›
Output:
[[6,1,2],[3,4,5]]
💡 Note:
After 1 shift: element 6 moves to [0][0], 1 moves to [0][1], 2 moves to [0][2], 3 moves to [1][0], etc.
Example 2 — Multiple Shifts
$
Input:
grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
›
Output:
[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
💡 Note:
After 4 shifts, the last row moves to the top and all other rows shift down by one position.
Example 3 — Full Cycle
$
Input:
grid = [[1,2,3],[4,5,6]], k = 6
›
Output:
[[1,2,3],[4,5,6]]
💡 Note:
After 6 shifts (m×n = 2×3 = 6), all elements return to their original positions.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m ≤ 50
- 1 ≤ n ≤ 50
- -1000 ≤ grid[i][j] ≤ 1000
- 0 ≤ k ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2×3 grid with elements [1,2,3,4,5,6]
2
Shift Operation
Each element moves right → next row → wraps to [0][0]
3
Output Grid
Grid after k=1 shifts
Key Takeaway
🎯 Key Insight: Use modular arithmetic to calculate final positions directly instead of simulating k shifts
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code