Skip to the code
cf.
+50 XP

#81 Rotate the Rings of a Grid

hard

A loading animation spins the rings of a grid of tiles. A ring is a layer of the grid: the outer border, then the border of what's inside it, and so on. The grid's smaller side is even, so every ring is a full loop.

One step moves every value one cell counterclockwise around its ring: along the top edge values move left, down the left edge they move down, along the bottom edge they move right, and up the right edge they move up.

Write rotateRings(grid, k) that returns the grid after k steps.

Example 1

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

2 moves left, 1 moves down, 3 moves right, and 4 moves up.

Example 2

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

The ring has 4 cells, so 4 steps bring every value back.

Constraints

  • 2 <= rows, cols <= 50
  • Math.min(rows, cols) is even.
  • 1 <= k <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).