LeetCode Β· #48
Rotate Image Solution
Rotate an n Γ n matrix 90Β° clockwise in-place.
01
Section One Β· Problem
Problem Statement
Example
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
02
Section Two Β· Approach 1
Extra Matrix β O(nΒ²) space
Create a new matrix and place new[j][n-1-i] = old[i][j].
Problem: O(nΒ²) extra space. In-place: transpose (swap rowsβcols) then reverse each row. Two passes, no extra space.
03
Section Three Β· Approach 2
Transpose + Reverse β O(nΒ²), O(1) space
Step 1: Transpose (swap matrix[i][j] with matrix[j][i]). Step 2: Reverse each row. The composition of these two operations equals a 90Β° clockwise rotation.
π‘ Mental model: Fold the matrix along its main diagonal (transpose). Then flip it left-to-right (reverse rows). The result is a 90Β° clockwise rotation. For counter-clockwise: reverse rows first, then transpose. Or: transpose then reverse columns.
π― Pattern: "In-place matrix rotation." Transpose + reverse is the elegant O(1) space approach. Works for any square matrix. For 180Β°: reverse each row, then reverse row order. For 270Β° (counter-clockwise): transpose, then reverse columns.
04
Section Four Β· Trace
Visual Walkthrough
Rotate Image β Transpose + Reverse
05
Section Five Β· Implementation
Code β Java & Python
Java
class Solution {
public void rotate(int[][] m) {
int n = m.length;
// Transpose for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int tmp = m[i][j]; m[i][j] = m[j][i]; m[j][i] = tmp;
}
// Reverse each row for (int[] row : m)
for (int l = 0, r = n - 1; l < r; l++, r--) {
int tmp = row[l]; row[l] = row[r]; row[r] = tmp;
}
}
}
Python
class Solution:
def rotate(self, m: list[list[int]]) -> None:
n = len(m)
for i in range(n):
for j in range(i + 1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
row.reverse()
06
Section Six Β· Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Extra matrix | O(nΒ²) | O(nΒ²) |
| Transpose + reverse β optimal | O(nΒ²) | O(1) |
07
Section Seven Β· Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| 1Γ1 | [[1]] | No change. |
| 2Γ2 | [[1,2],[3,4]] | β [[3,1],[4,2]]. |
| Even n | 4Γ4 | Works the same; no center element stays fixed. |
β Common Mistake: Transposing the full matrix β swapping (i,j) and (j,i) for ALL i,j. This swaps each pair twice, undoing the transpose. Only swap where
j > i (upper triangle).