Visualize

Pattern visualizer

Rotate Image

Rotating clockwise looks like it needs a second grid to avoid overwriting cells mid-rotation, but it decomposes into two simple in-place passes: transposing (flip across the main diagonal) turns rows into columns, and reversing each row afterward flips them left-right — together that's exactly a 90-degree clockwise turn, using zero extra memory. Animated on: matrix = [[1,2,3],[4,5,6],[7,8,9]] — rotate 90 degrees clockwise in place (shown flattened row-major)..

Transpose, then reverse each row — no extra grid needed

time O(n^2)space O(1) extrastep 1 / 9
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
8
[7]
9
[8]
line 2

3x3 matrix, flattened row-major (idx = row*3+col). Rotate 90 deg clockwise with no extra grid: transpose, then reverse each row.

Pseudocode
1FUNCTION rotate(matrix):
2 n = the number of rows in matrix
3 FOR i from 0 to n, j from i+1 to n:
4 swap matrix[i][j] with matrix[j][i] (transpose)
5 FOR each row:
6 reverse the row
7 RETURN matrix

← / → step · space play · Home restart

Where to practice Matrix