#1260
Shift 2D Grid
EasyArrayMatrixSimulationArrayCircular Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of simulating each shift, we can calculate the final position of each element directly. This reduces the number of operations significantly and allows us to achieve the result in a single pass.
⚙️
Algorithm
4 steps- 1Step 1: Flatten the 2D grid into a 1D array.
- 2Step 2: Calculate the effective shifts needed (k % total number of elements).
- 3Step 3: Rearrange the elements in the 1D array based on the effective shifts.
- 4Step 4: Convert the 1D array back into a 2D grid.
solution.py9 lines
1# Full working Python code
2
3def shiftGrid(grid, k):
4 m, n = len(grid), len(grid[0])
5 total_elements = m * n
6 k = k % total_elements
7 flat_grid = [grid[i][j] for i in range(m) for j in range(n)]
8 flat_grid = flat_grid[-k:] + flat_grid[:-k]
9 return [flat_grid[i * n:(i + 1) * n] for i in range(m)]ℹ
Complexity note: The time complexity is O(n) because we only traverse the grid a few times (flattening and rearranging), and the space complexity is O(n) due to the additional array used for flattening.
- 1Shifting elements in a 2D grid can be visualized as a circular queue operation.
- 2Understanding the effective number of shifts (k % total elements) can significantly reduce unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.