Ctrl K

Spin the Grid Rings

Medium
You get an m × n table grid, where m and n are both even, and a number k. The table splits into nested rings: the outer ring is its border, the next ring is the border of what remains after removing the outer ring, and so on towards the centre. One turn shifts every ring by one cell counter-clockwise: each number moves to the neighbouring cell of its ring in that direction. All rings turn at the same time and independently. Return the table after k turns.
Example 1
grid=[[1, 2], [3, 4]], k=1 → [[2, 4], [1, 3]]

There is a single ring, and every number moves one cell counter-clockwise: 2 goes left, 4 goes up, 3 goes right and 1 goes down.

Example 2
grid=[[5, 6, 7, 8], [9, 1, 2, 10], [11, 3, 4, 12], [13, 14, 15, 16]], k=13 → [[6, 7, 8, 10], [5, 2, 4, 12], [9, 1, 3, 16], [11, 13, 14, 15]]

The outer ring has 12 cells, so 13 steps are the same as one. The inner ring has 4 cells, and 13 steps are again the same as one.

Example 3
grid=[[1, 2, 3, 4], [5, 6, 7, 8]], k=6 → [[6, 5, 1, 2], [7, 8, 4, 3]]
Constraints
  • 2 ≤ m, n ≤ 50, both m and n are even
  • 1 ≤ grid[i][j] ≤ 5000
  • 1 ≤ k ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSpiral Readout MediumSpiral-Numbered Square MediumNext Step of a Cell Colony MediumZigzag Diagonal Sweep MediumMatch-Three Cascade Medium
loading Python…
Input
grid=[[1, 2], [3, 4]], k=1
Expected
[[2, 4], [1, 3]]

Run checks the first 3 tests in your browser. Submit checks all 47 tests on the server, hidden ones included.