08. Rotate Image (2D Matrix)
Given an $n \times n$ 2D matrix representing an image, rotate the image by 90 degrees clockwise in-place.
How It Works & Algorithmic Design
Mathematical transformation through Transpose then Reverse:
- Step 1: Transpose Matrix (Swap rows and columns across main diagonal):
- For every $i$ from $0$ to $n-1$ and $j$ from $i+1$ to $n-1$, swap
matrix[i][j]withmatrix[j][i].
- For every $i$ from $0$ to $n-1$ and $j$ from $i+1$ to $n-1$, swap
- Step 2: Reverse Each Row:
- For each row $i$, reverse elements horizontally (
leftandrightpointers swappingmatrix[i][left]andmatrix[i][right]).
- For each row $i$, reverse elements horizontally (
Why This Approach Works Best
Transpose + Reverse turns $90^\circ$ rotation into two clean, in-place matrix ops. Avoids $O(n^2)$ extra memory allocation, achieving true $O(1)$ space and $O(n^2)$ time complexity.
Example Walkthrough
[[1,2,3],[4,5,6],[7,8,9]]
3x3 matrix.
[[1,4,7],[2,5,8],[3,6,9]]
Rows converted to columns.
[[7,4,1],[8,5,2],[9,6,3]]
Each row reversed horizontally.
[[7,4,1],[8,5,2],[9,6,3]]
Rotated 90 degrees clockwise.
Answer: In-place 90-degree matrix rotation
function rotate(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
}Transpose matrix across diagonal, then reverse each row horizontally.
Rotate clockwise = Transpose matrix + Reverse rows.
Rotate counter-clockwise = Transpose matrix + Reverse columns.
Performs in-place updates achieving $O(1)$ extra space and $O(n^2)$ time.