AlgoViz

Rotate Image

Medium

90° in place · transpose + reverse

In simple words

Turn the grid 90° by flipping it over a diagonal and then mirroring each row.

The idea

Rotating 90° clockwise equals transposing the matrix (swap across the diagonal) and then reversing each row — both done in place with no extra grid.

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.

Finished the walkthrough? Add it to your streak.