1161. Alternating Ring Turns

Medium3.5 points estimatedMatrixSimulationArray

A display is an m x n grid of tiles where min(m, n) is even. Its tiles form concentric rectangular rings: ring 0 is the outer border, ring 1 is the border of what remains inside it, and so on. Because min(m, n) is even, every ring is a closed loop with at least two tiles on each side.

Modify grid in place and return nothing. Slide the values of ring 0 by k steps counterclockwise along their loop, the values of ring 1 by k steps clockwise, ring 2 counterclockwise again, and so on, alternating. Rings turn independently. Constraints: 2 <= m, n <= 50 and 1 <= k <= 10^9, so reduce k by the ring length. Aim for O(m * n) time and O(m + n) space.

Example 1

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

The only ring is the border; moving each value one step counterclockwise sends 1 down to the lower-left corner and gives [[2, 4], [1, 3]].

Example 2

Input:
grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]k = 1
Output:
[[2,3,4,8],[1,10,6,12],[5,11,7,16],[9,13,14,15]]
Explanation:

The outer ring turns counterclockwise by one step while the inner 2 x 2 ring turns clockwise by one step.

Example 3

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

The 6 border cells form one ring that moves two steps counterclockwise.

Constraints

2 ≤ m, n ≤ 50
min(m, n) is even
1 ≤ k ≤ 109
-109 ≤ grid[i][j] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from grid after your method returns.

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…