#48
Rotate Image
Medium Transpose + reverse rows
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Rotate an n × n matrix 90 degrees clockwise, in place.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: turn the picture 90° clockwise without a second matrix.
Why this works: transpose (mirror across the diagonal), then reverse each row. Together that's a clockwise turn.
Example: [[1,2,3],[4,5,6],[7,8,9]]
transpose → [[1,4,7],[2,5,8],[3,6,9]]reverse rows → [[7,4,1],[8,5,2],[9,6,3]]
✦Hints open one at a time
Transpose the matrix (swap across the main diagonal).
Then reverse each row.
↗Approach
Transpose by swapping matrix[i][j] with matrix[j][i] for j > i, then reverse every row. Together these equal a clockwise rotation. (Reversing columns instead gives counter-clockwise.)
</>Solution (Java)
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // only above the diagonal
int t = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = t;
}
}
for (int[] row : matrix) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int t = row[l];
row[l] = row[r];
row[r] = t;
}
}
}
}
!Common mistake
Transposing with j starting at 0, which swaps every pair twice and undoes the work.
Complexity
- Time: O(n²).
- Space: O(1).
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon