Problem Overview
- We are given a 2D matrix of size
n * n. - The matrix represents an image.
- Our goal is to rotate the image by 90 degrees clockwise.
- The solution must use constant extra space (in-place).
Example
Input:
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[[7,4,1],
[8,5,2],
[9,6,3]]
Intuition
If we remember basic matrix properties:
- Transpose of a matrix
- Reverse of each row
If we:
- First take the transpose (swap
(i,j)with(j,i)) - Then reverse every row
We effectively rotate the matrix 90° clockwise.
Why this works:

This is exactly a 90° clockwise rotation.
Approach
Step 1 — Transpose the Matrix
Swap:
matrix[i][j] ↔ matrix[j][i]
Important:
- Start
jfromi. - Otherwise you will swap elements twice.
Step 2 — Reverse Each Row
- Reverse only half of each row.
Edge Case:
- If we reverse the entire row twice, we get the original matrix.
- So only iterate till
n/2.
Optimal Solution
Code — Two Pointer Approach
| |
Code — Using Nested Loops
| |
Time & Space Complexity
Time: O(n²)
- Transpose → O(n²)
- Reverse → O(n²)
Space: O(1)
Final Takeaway
- Knowing matrix properties (like transpose) simplifies problems.
- Many in-place matrix transformations are combinations of smaller operations.
