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:
โข When reaching the end of a row, wrap to the beginning of next row:
โข The last element wraps around to the very beginning:
Given a 2D grid of size
๐ 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code