← Back to DSA Animator
Rotate Image LC #48 Medium Transpose + Reverse
Problem

You are given an n × n 2D matrix representing an image. Rotate the image 90° clockwise in-place. You must not allocate another 2D matrix.

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Explanation: Transpose then reverse each row.
Example 2
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Explanation: 4×4 matrix rotated 90° clockwise in-place.
Constraints: 1 ≤ n ≤ 20  |  −1000 ≤ matrix[i][j] ≤ 1000
Try Examples
Custom:
Approach
Two-step in-place rotation: Transpose (flip diagonal) then Reverse each row
Transpose: mat[i][j] ↔ mat[j][i] for i<j.  Reverse: swap mat[r][c] ↔ mat[r][n-1-c]
Matrix
Transformation Progress
Original
Transposed
Rotated
Variables
Phase
i
j / r
a ↔ b
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Observe: 90° CW rotation maps m[r][c] → m[c][n-1-r]
2
Transpose: swap m[i][j] ↔ m[j][i] for all j > i
3
Reverse rows: for each row, swap m[r][l] ↔ m[r][ri] moving inward
4
Result: matrix rotated 90° clockwise, fully in-place
Time
O(n²)
Space
O(1)
Why It Works

A 90° clockwise rotation sends element at [r][c] to [c][n-1-r].

Transpose sends [r][c] → [c][r]. Then reversing each row sends [c][r] → [c][n-1-r]. Combined: [r][c] → [c][n-1-r] — exactly the 90° CW rotation.

Both steps need only a single temp variable — truly O(1) extra space.