Home
DSA Patterns
Matrices
Rotate Image
Problem Understanding
Turn an n x n matrix, an image stored as a grid of pixels, a quarter turn clockwise. The rotation must happen in-place, inside the same matrix, without allocating a second one.
Strategy (Transpose + Reflect)
- Transpose: Swap
matrix[i][j]withmatrix[j][i]. - Reflect: Reverse each row.
Step 1: Transpose converts rows to columns.
Step 2: Reversing rows fixes the left-right order for 90 deg rotation.
Interactive Visualization
See the two-step process: Transpose then Reverse.
Dry Run
Matrix: [[1,2],[3,4]]
| Step | Action | State |
|---|---|---|
| 1 | Transpose | [[1,3],[2,4]] (Swap 2 & 3) |
| 2 | Reverse Row 0 | [[3,1],[2,4]] |
| 3 | Reverse Row 1 | [[3,1],[4,2]] |
Result: 90 deg clockwise rotation.
Edge Cases & Checks
Validation points:
Square Matrix: Problem usually guarantees n x n. If not, this method fails.
Clockwise vs Counter: For Counter-Clockwise, Reverse then Transpose.
Solution
O(N^2) Time, O(1) Space.
Rotate Image Code
1var rotate = function(matrix) {2 const n = matrix.length;3 // Transpose4 for (let i = 0; i < n; i++) {5 for (let j = i; j < n; j++) {6 [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];7 }8 }9 // Reflect10 for (let i = 0; i < n; i++) {11 matrix[i].reverse();12 }13};
