DSA Tracker

Visualize

Rotate Image

Transpose, then reverse each row — no extra grid needed

time O(n^2)space O(1) extra

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.

Details

Animated on: matrix = [[1,2,3],[4,5,6],[7,8,9]] — rotate 90 degrees clockwise in place (shown flattened row-major).

Problem:Rotate ImageMedium

Transpose, then reverse each row — no extra grid needed

step 1 / 9

1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
8
[7]
9
[8]

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

Every step in words

Show all 9 steps
  1. 3x3 matrix, flattened row-major (idx = row*3+col). Rotate 90 deg clockwise with no extra grid: transpose, then reverse each row.
  2. Transpose: swap (0,1) and (1,0) -> flattened idx 1 and 3.
  3. Transpose: swap (0,2) and (2,0) -> flattened idx 2 and 6.
  4. Transpose: swap (1,2) and (2,1) -> flattened idx 5 and 7.
  5. Transpose complete — rows and columns are swapped. Now reverse each row to finish the clockwise rotation.
  6. Reverse row 0 (flattened idx 0..2) -> [7, 4, 1].
  7. Reverse row 1 (flattened idx 3..5) -> [8, 5, 2].
  8. Reverse row 2 (flattened idx 6..8) -> [9, 6, 3].
  9. Rotation complete: [[7,4,1], [8,5,2], [9,6,3]].

Now solve it yourself

Watching is the first half. The second is writing it without the animation.