Skip to problem
←

Rotate Image

Medium 0 attempts

Given an n × n integer matrix, rotate its values 90 degrees clockwise in place.

Modify the supplied matrix using constant extra space; do not allocate a second matrix. The function's return value is ignored. Every original cell (r, c) moves to (c, n - 1 - r).

For [[1, 2], [3, 4]], the result is [[3, 1], [4, 2]]. The original top row becomes the rightmost column, read from top to bottom. A one-cell matrix is unchanged. Negative and repeated values follow the same positional rotation.

Function contract

Implement rotate(matrix).

Output: Modify argument 1 in place. The editor compares its final value; the function return value is ignored.

Example 1

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]

Example 2

Input
matrix = [[1]]
Output
[[1]]
Visual Aid
A quarter turn clockwise
Clockwise matrix rotationBefore: top row 1, 2; bottom row 3, 4. After a clockwise quarter turn: top row 3, 1; bottom row 4, 2.1234314290° clockwiseBeforeAfter

The top row [1, 2] becomes the rightmost column.

Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

Transpose, Then Reverse Each Row

First swap every pair across the main diagonal. Visit only positions above it (j > i) so each pair is swapped once and diagonal cells stay in place.

Then reverse each row. Transposition sends (r, c) to (c, r); reversing rows sends that to (c, n - 1 - r), exactly the clockwise rotation mapping. Reversing columns instead would rotate in the opposite direction.

Both steps mutate the existing matrix and use only constant temporary storage.

javascript
function rotate(matrix) {
  const n = matrix.length;
  for (let i = 0; i < n; i++)
    for (let j = i + 1; j < n; j++)
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
  for (const row of matrix) row.reverse();
}

Time: O(n²) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript