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 to grid[i][j + 1]
  • Element at grid[i][n - 1] moves to grid[i + 1][0]
  • Element at grid[m - 1][n - 1] moves to grid[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
Shift 2D Grid - Mathematical Position Mapping INPUT 2D Grid (2x3): 1 2 3 4 5 6 [0,0] [0,1] [0,2] r0 r1 Flattened (1D view): 1 2 3 4 5 6 Input Values: grid = [[1,2,3], [4,5,6]] k = 1 m = 2, n = 3 ALGORITHM STEPS 1 Calculate Total Size total = m * n = 6 2 Normalize k k = k % total = 1 % 6 = 1 3 Position Mapping new_pos = (old + k) % total old_idx --> new_idx 0 --> (0+1)%6 = 1 1 --> (1+1)%6 = 2 2 --> (2+1)%6 = 3 3 --> (3+1)%6 = 4 4 --> (4+1)%6 = 5 5 --> (5+1)%6 = 0 6 wraps to position 0! 4 Convert to 2D row = idx / n, col = idx % n Rebuild the 2D grid FINAL RESULT After shift by k=1: 6 1 2 3 4 5 wrapped 6 shifts from end to start Reshaped 2D Grid: 6 1 2 3 4 5 Output: [[6,1,2],[3,4,5]] OK - Grid shifted right by 1 Key Insight: Treat the 2D grid as a 1D array using index = row * n + col. Shifting becomes a simple circular rotation: new_index = (old_index + k) % total. Convert back using row = idx/n, col = idx%n. Time: O(m*n) | Space: O(m*n) for the result grid. Modulo handles wrap-around elegantly. TutorialsPoint - Shift 2D Grid | Mathematical Position Mapping Approach
Asked in
Amazon 15 Microsoft 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen