KatInterview

Clockwise Rotation with Frozen Diagonals

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingmatrixsimulationrotation

Last updated

Simulate clockwise 90° rotation on a square grid while keeping all main-diagonal and anti-diagonal elements fixed in place.

You are given an n × n square matrix and an integer k representing the number of clockwise 90-degree rotations to perform. However, certain cells must remain frozen: any cell that lies on the main diagonal or the anti-diagonal stays in place throughout all rotations.

A cell at position (row, col) (zero-indexed) is considered frozen if:

  • row == col (main diagonal), or
  • row + col == n - 1 (anti-diagonal)

For each rotation, every non-frozen cell at position (row, col) moves to position (col, n - 1 - row), exactly as it would in a standard clockwise 90-degree matrix rotation. Frozen cells never move and retain their original values.

Perform exactly k rotations and return the resulting matrix.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ k ≤ 4
  • All matrix elements are integers in the range [-1000000000, 1000000000]

Examples

Example 1

Input: rotate_with_frozen_diagonals([[1, 2, 3, 4, 5], [2, 1, 9, 6, 3], [7, 0, 4, 8, 1], [5, 2, 4, 1, 9], [6, 4, 3, 2, 1]], 1)

Output: [[1, 5, 7, 2, 5], [4, 1, 0, 6, 2], [3, 4, 4, 9, 3], [2, 2, 8, 1, 4], [6, 9, 1, 3, 1]]

Example 2

Input: rotate_with_frozen_diagonals([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 2)

Output: [[1, 8, 3], [6, 5, 4], [7, 2, 9]]

Example 3

Input: rotate_with_frozen_diagonals([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 1)

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

Hints

Hint 1

A standard clockwise rotation maps cell (r, c) to (c, n-1-r). Apply this transformation only to cells that are not on either diagonal.

Hint 2

Use a temporary matrix to avoid overwriting values you still need to read during the same rotation step.

Hint 3

Notice that after 4 rotations, non-diagonal cells return to their original positions, forming complete cycles.