Shift 2D Grid
EasyPrompt
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 togrid[i][j + 1]. - Element at
grid[i][n - 1]moves togrid[i + 1][0]. - Element at
grid[m - 1][n - 1]moves togrid[0][0].
Return the 2D grid after applying shift operation k times.
Example 1:
gridExample 2:
gridExample 3:
grid
Constraints:
m == grid.lengthn == grid[i].length1 <= m <= 501 <= n <= 50-1000 <= grid[i][j] <= 10000 <= k <= 100
Approaches
3 approaches with complexity analysis and trade-offs.
This approach directly simulates the shifting process as described in the problem. It iterates k times, and in each iteration, it calculates the new position of every element after one shift and stores it in a temporary grid. After all elements are moved, the temporary grid's contents are copied back to the original grid for the next iteration.
Algorithm
- Loop
ktimes to simulate each shift. - In each iteration, create a new temporary grid
tempGridof sizem x n. - Iterate through each cell
(i, j)of the inputgrid. - Calculate the new position
(newI, newJ)after one single shift:- If
j < n - 1, the element moves to(i, j + 1). - If
j == n - 1andi < m - 1, the element moves to(i + 1, 0). - If
i == m - 1andj == n - 1, the element moves to(0, 0).
- If
- Place the element
grid[i][j]intotempGridat the calculated new position. - After iterating through all cells, replace the original
gridwithtempGrid. - After
kiterations, convert the finalgridinto aList<List<Integer>>and return it.
Walkthrough
The algorithm performs the shift operation k times. For each of the k steps, a new m x n grid, newGrid, is created to store the state after one shift. We iterate through each cell (i, j) of the current grid. The value grid[i][j] is placed into its new position in newGrid based on the shift rules. After iterating through all cells, the grid is updated with the contents of newGrid. This process is repeated k times. Finally, the grid is converted to the required list format.
class Solution { public List<List<Integer>> shiftGrid(int[][] grid, int k) { int m = grid.length; int n = grid[0].length; for (int shift = 0; shift < k; shift++) { int[][] newGrid = new int[m][n]; // Case 1: Element at grid[i][j] moves to grid[i][j + 1] for (int i = 0; i < m; i++) { for (int j = 0; j < n - 1; j++) { newGrid[i][j + 1] = grid[i][j]; } } // Case 2: Element at grid[i][n - 1] moves to grid[i + 1][0] for (int i = 0; i < m - 1; i++) { newGrid[i + 1][0] = grid[i][n - 1]; } // Case 3: Element at grid[m - 1][n - 1] moves to grid[0][0] newGrid[0][0] = grid[m - 1][n - 1]; grid = newGrid; } List<List<Integer>> result = new ArrayList<>(); for (int[] row : grid) { List<Integer> listRow = new ArrayList<>(); for (int cell : row) { listRow.add(cell); } result.add(listRow); } return result; }}Complexity
Time
O(k * m * n). For each of the `k` shifts, we iterate over all `m * n` elements.
Space
O(m * n). A temporary grid of size `m * n` is created in each of the `k` iterations.
Trade-offs
Pros
Simple to understand and implement as it directly follows the problem description.
Cons
Highly inefficient for large values of
k, as the entire grid is processedktimes.Creates a new grid in every iteration, leading to high memory churn.
This approach recognizes that the 2D grid shift is equivalent to a 1D circular array rotation. The grid is first flattened into a 1D array. Then, a circular shift of k positions is applied to this 1D array. Finally, the shifted 1D array is converted back into an m x n grid.
Algorithm
- Get grid dimensions
mandn. Calculate total elementstotal = m * n. - Flatten the 2D
gridinto a 1D array or list, sayflatList. - The shift operation on the 2D grid is equivalent to a right circular shift on the 1D list. The number of effective shifts is
k % total. - Create a new 1D list,
rotatedList, to store the result of the shift. - Populate
rotatedListby taking the lastk % totalelements offlatListfollowed by the firsttotal - (k % total)elements. - Create a new
m x nresult grid. - Reconstruct the 2D grid by populating it with elements from
rotatedList. The element atrotatedList[p]goes toresult[p / n][p % n]. - Return the result grid.
Walkthrough
The core idea is to simplify the 2D shift into a 1D rotation. First, we calculate the total number of elements, total = m * n. Since shifting total times brings the grid back to its original state, we only need to consider the effective number of shifts, k % total. We create a temporary 1D array and populate it with the elements of the grid. Then, we create a new 1D array for the shifted elements. The element at index p in the flattened array moves to the new index (p + k) % total. Finally, we construct the result 2D grid from this shifted 1D array.
class Solution { public List<List<Integer>> shiftGrid(int[][] grid, int k) { int m = grid.length; int n = grid[0].length; int total = m * n; k = k % total; List<Integer> flatList = new ArrayList<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { flatList.add(grid[i][j]); } } // Reverse the entire list Collections.reverse(flatList); // Reverse the first k elements Collections.reverse(flatList.subList(0, k)); // Reverse the remaining elements Collections.reverse(flatList.subList(k, total)); List<List<Integer>> result = new ArrayList<>(); for (int i = 0; i < m; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j < n; j++) { row.add(flatList.get(i * n + j)); } result.add(row); } return result; }}Complexity
Time
O(m * n). We iterate through the grid elements to flatten, perform the rotation (which is also O(m*n)), and then reconstruct the grid.
Space
O(m * n). We use an auxiliary 1D list of size `m * n`.
Trade-offs
Pros
Much more efficient than simulation for large
kas its complexity is independent ofk.Conceptually clean by reducing a 2D problem to a 1D one.
Cons
Requires extra space proportional to the size of the grid for the intermediate 1D list.
Involves multiple passes over the data: one to flatten, one to shift, and one to reconstruct.
This is the most efficient approach. Instead of simulating or using intermediate data structures, we directly compute the final grid. For each cell (i, j) in the original grid, we calculate where it will end up after k shifts. This is done by converting the 2D coordinates to a 1D index, applying the shift arithmetically, and converting the result back to 2D coordinates for the new grid.
Algorithm
- Get grid dimensions
mandn. Calculate total elementstotal = m * n. - Create a new result grid
resultGridof sizem x n. - Iterate through each cell
(i, j)of the originalgrid. - For each element
grid[i][j], calculate its 1D index:oldIndex1D = i * n + j. - Calculate its new 1D index after
kshifts:newIndex1D = (oldIndex1D + k) % total. - Convert the
newIndex1Dback to 2D coordinates:newI = newIndex1D / n,newJ = newIndex1D % n. - Place the element in the new grid:
resultGrid[newI][newJ] = grid[i][j]. - After iterating through all elements, convert
resultGridto the requiredList<List<Integer>>format and return it.
Walkthrough
The key insight is that we can determine the final position of any element with a simple formula. We create a new result grid and iterate through each cell (i, j) of the original grid. For each element, we map its 2D coordinates (i, j) to a 1D index p = i * n + j. After k shifts, its new 1D index will be p_new = (p + k) % (m * n). We then convert this new 1D index back to 2D coordinates (new_i, new_j) and place the element grid[i][j] at result[new_i][new_j]. This process fills the new grid in a single pass over the original grid.
class Solution { public List<List<Integer>> shiftGrid(int[][] grid, int k) { int m = grid.length; int n = grid[0].length; int total = m * n; // The result format is List<List<Integer>>, so we create it upfront. // Initialize with placeholder values. List<List<Integer>> result = new ArrayList<>(); for (int i = 0; i < m; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j < n; j++) { row.add(0); } result.add(row); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int oldIndex1D = i * n + j; int newIndex1D = (oldIndex1D + k) % total; int newI = newIndex1D / n; int newJ = newIndex1D % n; result.get(newI).set(newJ, grid[i][j]); } } return result; }}Complexity
Time
O(m * n). We iterate through the grid once to compute the new grid. The modulo and division operations are constant time.
Space
O(m * n). This space is used for the result grid, which is required by the problem's return type. The auxiliary space besides the output is O(1).
Trade-offs
Pros
Most efficient time complexity, O(m * n), independent of
k.Single-pass solution over the grid elements.
Avoids creating large intermediate data structures beyond the required result grid.
Cons
Requires space for the new grid, although this is generally required for the return type anyway.
Solutions
Solution
class Solution {public List<List<Integer>> shiftGrid(int[][] grid, int k) { int m = grid.length, n = grid[0].length; List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < m; ++i) { List<Integer> row = new ArrayList<>(); for (int j = 0; j < n; ++j) { row.add(0); } ans.add(row); } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int idx = (i * n + j + k) % (m * n); int x = idx / n, y = idx % n; ans.get(x).set(y, grid[i][j]); } } return ans; }}class Solution {public: vector<vector<int>> shiftGrid(vector<vector<int>> &grid, int k) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> ans(m, vector<int>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int idx = (i * n + j + k) % (m * n); int x = idx / n, y = idx % n; ans[x][y] = grid[i][j]; } } return ans; }};class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ in range(m)] for i, row in enumerate(grid): for j, v in enumerate(row): x, y = divmod((i * n + j + k) % (m * n), n) ans[x][y] = v return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.