medium +20 pts

Shift 2D Grid

Shift every element of a 2D grid to the right by k positions, wrapping around.

Write a function `shift_grid(grid, k)` that returns a new 2D list representing the grid after shifting every element to the right by `k` positions, where the shift wraps around the flattened grid. To shift the grid: 1. Flatten the grid into a 1D list by reading all rows from top to bottom, left to right. 2. Shift this list to the right by `k` positions, meaning the element at index `i` in the original flattened list moves to index `(i + k) % (rows * cols)`. 3. Reshape the shifted 1D list back into a grid with the same number of rows and columns. The input grid is a non-empty 2D list (list of lists) of integers, and `k` is a non-negative integer. The dimensions of the grid should be preserved. You must implement `shift_grid(grid, k)` that returns the shifted grid.

Constraints

Grid dimensions at most 10x10, k up to 1000. Time complexity O(rows*cols), space O(rows*cols).

Example

>>> shift_grid([[1,2],[3,4]], 1)
[[4,1],[2,3]]
>>> shift_grid([[1,2,3],[4,5,6],[7,8,9]], 2)
[[8,9,1],[2,3,4],[5,6,7]]
>>> shift_grid([[1,2,3,4],[5,6,7,8]], 10)
[[5,6,7,8],[1,2,3,4]]
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Flatten the grid into a single list using nested loops or a comprehension.
The new index for each element is (old_index + k) % total_cells.
After shifting, rebuild the grid with the original number of rows and columns.
You can use modulo to wrap the shift even if k is larger than the total number of elements.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.