Shift 2D Grid (LeetCode 1260): Solution and Explanation

Easy
Array
Matrix
Simulation

Shift every value of an m x n grid forward by one cell k times, where a value at the end of a row moves to the start of the next row and the last cell wraps to the first. Return the shifted grid.

Intuition

Look at what one shift does in reading order. Each value moves one step to the right, the value at the end of a row continues at the start of the next row, and the very last value goes to the very first cell. That is exactly a rotation of a list, as long as you read the grid row by row.

So flatten the grid in your head: cell (i, j) sits at position i * n + j in a list of m * n values. One shift moves position p to p + 1, and the last position wraps to 0. Shifting k times moves p to (p + k) % (m * n).

Because the rotation is circular, m * n shifts bring the grid back to where it started. Reducing k %= m * n first keeps the arithmetic small, although the modulo in the destination formula would handle a large k anyway.

Finally, a list position p converts back to a cell with row p // n and column p % n. Writing each value straight into its destination in a fresh grid finishes the job in one pass.

Approach: Flatten and rotate by index

  1. Let total = m * n and reduce k %= total.
  2. Create result, an empty m x n grid.
  3. For every cell (i, j), compute dest = (i * n + j + k) % total.
  4. Write grid[i][j] into result[dest // n][dest % n].
  5. Return result.

Step-by-step example

grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
  1. m = 3, n = 3, total = 9, and k % 9 = 1.
  2. 1 is at position 0 and moves to 1, which is result[0][1]. 2 moves from 1 to 2, result[0][2].
  3. 3 is at position 2 and moves to 3, which is result[1][0]: the end of row 0 continues at the start of row 1.
  4. The values 4 to 8 each move one position forward the same way.
  5. 9 is at position 8; 8 + 1 = 9 wraps to 0, so it lands in result[0][0].
  6. The result is [[9,1,2],[3,4,5],[6,7,8]].

Code: Python, Java, C++

1class Solution:
2    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
3        m, n = len(grid), len(grid[0])
4        total = m * n
5        k %= total
6        result = [[0] * n for _ in range(m)]
7        for i in range(m):
8            for j in range(n):
9                dest = (i * n + j + k) % total
10                result[dest // n][dest % n] = grid[i][j]
11        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each cell is read once and written once, and the destination is computed in constant time.

Space

O(m * n)

The result grid has the same size as the input. Apart from the output, only a few integers are used.

Other approaches

Simulate k single shifts (time O(k * m * n), space O(m * n))

Move every value one cell forward, k times. It follows the statement literally but costs O(k * m * n).

In-place rotation by three reversals (time O(m * n), space O(1))

Treat the grid as a flat array and rotate it right by k with the reverse-all, reverse-first-k, reverse-rest trick from Rotate Array, indexing cells through p // n and p % n. It avoids the extra grid.

Common mistakes

  • Shifting each row independently. A value at the end of a row moves to the next row, not to the start of the same row.
  • Using m instead of n when converting a position back to a cell. The row is p // n and the column is p % n, where n is the number of columns.
  • Forgetting the wrap from the last cell to the first, which the modulo by m * n handles.
  • Writing into the input grid while still reading from it, which overwrites values before they move.

Frequently asked questions

Why reduce k modulo m * n?

After m * n shifts every value has gone all the way around and is back in place, so only the remainder changes the result.

Is this the same as Rotate Array?

Yes. Read row by row, the grid is an array, and k shifts are a right rotation by k. The only extra work is converting between positions and (row, column) pairs.

What happens when k is 0?

Every destination equals its source, so the result is a copy of the original grid.