KatInterview

Rotate a Square Matrix 90° Clockwise In Place

Arrays & HashingAuto-graded · 16 test cases
MediumAuto-gradedArrays & Hashingmatrixin-placetwo-pointer

Last updated

Tests whether a candidate can transform an n×n grid in place using transpose and row-reversal, with no extra matrix allocated.

Rotate a Square Matrix 90° Clockwise In Place

You are given an n × n grid of integers. Rotate the entire grid a quarter-turn clockwise, modifying it directly without allocating a second matrix. Return the modified grid.

A 90° clockwise rotation moves every cell at row i, column j to row j, column n − 1 − i.

For example, the top-left corner ends up at the top-right, and the bottom-left corner ends up at the top-left.

What "in place" means here

You may use a constant amount of extra memory (a few temporary variables for swaps). You may not create a full copy of the matrix or any structure proportional to n².

Constraints

  • 1 ≤ n ≤ 20
  • The matrix is always square (n rows, each with exactly n elements).
  • -1000 ≤ matrix[i][j] ≤ 1000
  • The input is modified directly; the same object must be returned.

Examples

Example 1

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

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

Example 2

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

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

Hints

Hint 1

A 90° clockwise rotation can be decomposed into two simpler operations that each only touch pairs of elements. What two things happen to a matrix when you rotate it?

Hint 2

Try transposing first: swap every element at position (i, j) with the element at (j, i), but only for pairs where j > i so you don't swap twice. After that, look at what each row needs to become.

Hint 3

After the transpose, each row is the mirror image of what it should be. Reversing every row in place finishes the job — and both steps together use only O(1) extra space.