1260. Shift 2D Grid
- Array
- Matrix
- Simulation
TIME
O(m * n)
SPACE
O(m * n)
Intuition
The three shift rules together describe one simple thing: read the grid in row-major order and everything moves one step forward, wrapping from the last cell back to the first. So the 2D shift is just a right rotation of the flattened 1D array, and applying it k times is a rotation by k.
Since rotating by m * n returns the grid to its original state, only k mod (m * n) matters, no need to loop k times.
Approach
- Let
total = m * nand reducek %= total. - For each cell
(i, j), its flat index isidx = i * n + j; it moves to flat index(idx + k) % total. - Write each value into a fresh result grid at row
newIdx / n, columnnewIdx % n.
Complexity
- Time: O(m · n), a single pass, independent of
k - Space: O(m · n), the output grid
Edge Cases
k = 0→ grid unchangedka multiple ofm * n(Example 3) → unchanged after the modulok > m * n→ handled by the modulo- Single row or single column → still a plain rotation of the flattened order
- Negative values are just data; they don't affect the index math
Code
from typing import List
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
"""
1260. Shift 2D Grid
Time: O(m * n)
Space: O(m * n)
"""
m, n = len(grid), len(grid[0])
total = m * n
k %= total # full rotations are no-ops
result = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
new_idx = (i * n + j + k) % total
result[new_idx // n][new_idx % n] = grid[i][j]
return resultimport java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 1260. Shift 2D Grid
* Time: O(m * n)
* Space: O(m * n)
*/
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
int m = grid.length, n = grid[0].length;
int total = m * n;
k %= total; // full rotations are no-ops
Integer[][] result = new Integer[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int newIdx = (i * n + j + k) % total;
result[newIdx / n][newIdx % n] = grid[i][j];
}
}
List<List<Integer>> out = new ArrayList<>();
for (Integer[] row : result) {
out.add(Arrays.asList(row));
}
return out;
}
}