AlgoViz

Rotate matrix by 90 degrees

Medium

Transpose, then reverse each row

Problem

Given an N * N 2D integer matrix, rotate the matrix by 90 degrees clockwise. The rotation must be done in place, meaning the input 2D matrix must be modified directly.

In simple words

Transpose the grid (swap rows/columns), then reverse each row — that's a 90° turn.

The idea

Transposing swaps rows with columns, and reversing each row afterwards completes the clockwise quarter turn. Both steps are in place, so the whole rotation needs no second matrix.

The trick

  • Transpose only the upper triangle (j > i) or you undo your own swaps.
  • Anticlockwise is transpose then reverse each column instead.
  • O(n²) time, O(1) space.
1
2
3
4
5
6
7
8
9

Step 1 of 8. Rotate 90° clockwise = transpose (swap across the diagonal), then reverse each row.

1/8
Optimal
timeO(n²)spaceO(1)

Two in-place passes.

1for (let i=0;i<n;i++) for (let j=i+1;j<n;j++)2  [M[i][j], M[j][i]] = [M[j][i], M[i][j]];   // transpose3for (const row of M) row.reverse();          // mirror

Input

grid
3 × 3

Memory

cells marked
0

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Explanation:
Each column becomes a row.

Example 2

Input:
matrix = [[1,2],[3,4]]
Output:
[[3, 1], [4, 2]]
Explanation:
Turns 90° clockwise to [[3,1],[4,2]].

Example 3

Input:
matrix = [[1]]
Output:
[[1]]
Explanation:
One cell stays put.

Constraints

  • n == matrix.length.
  • n == matrix[i].length.
  • 1 <= n <= 100.
  • -10^4 <= matrix[i][j] <= 10^4

Finished the walkthrough? Add it to your streak.