204. Shift the Grid

A rectangular tray of tiles is stored in grid. One shift moves every tile one position to the right, in reading order: the tile at [i][j] moves to [i][j + 1], the tile at the end of a row moves to the start of the next row, and the tile in the bottom-right corner wraps around to the top-left corner [0][0].

Apply the shift exactly k times and return the resulting grid. Note that k can be very large, much larger than the number of tiles, so simulating the shifts one by one would be far too slow.

Example 1

Input:
grid = [[4,7,1],[2,9,5]], k = 2
Output:
[[9,5,4],[7,1,2]]
Explanation:

Reading the tiles in order gives 4,7,1,2,9,5. Two shifts move the last two tiles to the front: 9,5,4,7,1,2.

Example 2

Input:
grid = [[8]], k = 5
Output:
[[8]]
Explanation:

A one-tile grid never changes.

Example 3

Input:
grid = [[1,2],[3,4],[5,6]], k = 4
Output:
[[3,4],[5,6],[1,2]]
Explanation:

There are 6 tiles, so 4 shifts to the right put the last 4 tiles first: 3,4,5,6,1,2.

Constraints

1 ≤ grid.length, grid[0].length ≤ 50
-1000 ≤ grid[i][j] ≤ 1000
0 ≤ k ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(m × n)
Space
O(m × n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…