Problem 253238 · hard · Phase 02 Linear Data Structures

Turning the Gear Rings

matrices · rotation · modular arithmetic · simulation

A machine face is an m x n grid of numbers, built from concentric rings of cells. Ring 0 is the outer border, ring 1 is the border of what remains after removing ring 0, and so on, until no cells are left.

List the cells of each ring clockwise, starting at its top-left cell: along its top row to the right, down its right column, along its bottom row to the left, and up its left column. A ring that is a single row is listed left to right; a ring that is a single column is listed top to bottom.

The rings are gears, so neighbouring rings turn in opposite directions. Ring 0 turns forward by k steps, ring 1 backward by k steps, ring 2 forward, and so on. One forward step moves every value in a ring to the next cell in its list (the last cell's value moves to the first cell). One backward step moves every value to the previous cell (the first cell's value moves to the last).

Return the grid after the turn as a new list of lists. Return [] for an empty grid.

Examples

Input:  grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], k = 1
Output: [[5, 1, 2, 3], [9, 7, 11, 4], [13, 6, 10, 8], [14, 15, 16, 12]]
Explanation: the outer ring moves one cell clockwise; the inner 2x2 ring [6, 7, 11, 10]
moves one cell backward, becoming [7, 11, 10, 6].

Input:  grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], k = 1
Output: [[5, 1, 2, 3], [9, 7, 6, 4], [10, 11, 12, 8]]
Explanation: ring 1 is the single row [6, 7]; one backward step swaps it.

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

Constraints

  • 0 <= m, n <= 300; every row has the same length.
  • 0 <= k <= 10**9
  • Do not modify grid.
  • Target: O(m * n) time, whatever the value of k.

Goals

  • Peel a matrix into concentric rings and list each ring's cells in order
  • Rotate each ring by k modulo its own length
  • Handle rings that collapse to a single row or column
Starting Python…