Shift 2D Grid - Problem
Imagine you have a 2D grid filled with numbers, and you need to shift all elements in a specific pattern multiple times. Each shift operation moves every element to the next position following these rules:

๐Ÿ“ Shift Rules:
โ€ข Elements move right within their row: grid[i][j] โ†’ grid[i][j+1]
โ€ข When reaching the end of a row, wrap to the beginning of next row: grid[i][n-1] โ†’ grid[i+1][0]
โ€ข The last element wraps around to the very beginning: grid[m-1][n-1] โ†’ grid[0][0]

Given a 2D grid of size m ร— n and an integer k, return the grid after performing exactly k shift operations.

Input & Output

example_1.py โ€” Basic 2x3 Grid
$ Input: grid = [[1,2,3],[4,5,6]], k = 1
โ€บ Output: [[6,1,2],[3,4,5]]
๐Ÿ’ก Note: After 1 shift: 1โ†’2's position, 2โ†’3's position, 3โ†’4's position (wrap to next row), 4โ†’5's position, 5โ†’6's position, 6โ†’1's position (wrap to start)
example_2.py โ€” 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 entire bottom row moves to the top, and all other rows shift down by one position
example_3.py โ€” Edge Case: k > grid size
$ Input: grid = [[1,2],[3,4]], k = 6
โ€บ Output: [[3,4],[1,2]]
๐Ÿ’ก Note: Since grid has 4 elements total, k=6 is equivalent to k=6%4=2 shifts. After 2 shifts: bottom row becomes top row

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m โ‰ค 50
  • 1 โ‰ค n โ‰ค 50
  • 1 โ‰ค grid[i][j] โ‰ค 100
  • 1 โ‰ค k โ‰ค 100

Visualization

Tap to expand
๐Ÿญ Conveyor Belt Factory Visualization123456๐Ÿ”„ Circular Pattern: Items flow right โ†’ down โ†’ wrap aroundGreen arrows: Normal flow | Red dashed: Wrap-around๐Ÿ’ก Mathematical Insightnew_pos = (old_pos + k) % totalSkip simulation, calculate directly!
Understanding the Visualization
1
Snake Pattern
Items flow left-to-right on each level, then drop to the next level
2
Circular Loop
Last item wraps around to the very beginning, creating a cycle
3
Direct Calculation
Use math to predict final positions without moving items step-by-step
4
Efficient Result
All items reach their destinations in a single operation
Key Takeaway
๐ŸŽฏ Key Insight: The 2D grid shifts follow a predictable circular pattern. By treating it as a 1D array and using modular arithmetic, we can calculate final positions directly without simulating each individual shift, achieving optimal O(mร—n) performance.
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.4K 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