Rotate Image
Transpose, then reverse each row — no extra grid needed
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
3x3 matrix, flattened row-major (idx = row*3+col). Rotate 90 deg clockwise with no extra grid: transpose, then reverse each row.
1FUNCTION rotate(matrix):2 n = the number of rows in matrix3 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 row7 RETURN matrix
← / → step · space play · Home restart
Every step in words
Show all 9 steps
- 3x3 matrix, flattened row-major (idx = row*3+col). Rotate 90 deg clockwise with no extra grid: transpose, then reverse each row.
- Transpose: swap (0,1) and (1,0) -> flattened idx 1 and 3.
- Transpose: swap (0,2) and (2,0) -> flattened idx 2 and 6.
- Transpose: swap (1,2) and (2,1) -> flattened idx 5 and 7.
- Transpose complete — rows and columns are swapped. Now reverse each row to finish the clockwise rotation.
- Reverse row 0 (flattened idx 0..2) -> [7, 4, 1].
- Reverse row 1 (flattened idx 3..5) -> [8, 5, 2].
- Reverse row 2 (flattened idx 6..8) -> [9, 6, 3].
- 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.