Rotate Image
Rotate an n×n matrix 90° clockwise in place — transpose then reverse each row (or layer peel).
- dsa
- arrays
- interview
- Meta
The problem
Rotate an n × n matrix 90 degrees clockwise in place. Do not allocate another matrix for the answer (O(1) extra space).
Input:
[[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[[7,4,1],
[8,5,2],
[9,6,3]]
Mapping: element at (r, c) goes to (c, n - 1 - r).
Brute force
Build a new matrix with the mapping. Correct, O(n²) space — not allowed if they insist on in-place.
function rotateCopy(matrix: number[][]): number[][] {
const n = matrix.length;
const out = Array.from({ length: n }, () => Array(n).fill(0));
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
out[c][n - 1 - r] = matrix[r][c];
}
}
return out;
}
Optimal: transpose + reverse rows
- Transpose — swap
matrix[r][c]withmatrix[c][r]forc > r. - Reverse each row.
That composition is 90° clockwise. (Counter-clockwise: reverse rows first, then transpose — or transpose then reverse columns.)
function rotate(matrix: number[][]): void {
const n = matrix.length;
// transpose
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
[matrix[r][c], matrix[c][r]] = [matrix[c][r], matrix[r][c]];
}
}
// reverse each row
for (let r = 0; r < n; r++) {
matrix[r].reverse();
}
}
Layer-by-layer four-way swap
function rotateLayers(matrix: number[][]): void {
const n = matrix.length;
for (let layer = 0; layer < Math.floor(n / 2); layer++) {
const first = layer;
const last = n - 1 - layer;
for (let i = first; i < last; i++) {
const offset = i - first;
const top = matrix[first][i];
// left -> top
matrix[first][i] = matrix[last - offset][first];
// bottom -> left
matrix[last - offset][first] = matrix[last][last - offset];
// right -> bottom
matrix[last][last - offset] = matrix[i][last];
// top -> right
matrix[i][last] = top;
}
}
}
| Time | O(n²) |
| Space | O(1) |
Edge cases
n = 1no-op- Even vs odd n (center cell fixed in odd)
- Rectangle is out of scope — problem is square
Common bugs
- Transposing full double loop and double-swapping back
- Rotating counter-clockwise by mistake
- Cloning rows incorrectly (
matrix[r] = matrix[r].reverse()is fine in place)
Interview delivery
- State (r,c) → (c, n-1-r).
- Transpose + reverse (clean).
- Or four-cycles per layer.
- O(n²)/O(1).
- Follow-up: rotate 180, anti-clockwise.
Related
Mapping check
n=3: (0,0)→(0,2), (0,1)→(1,2), (0,2)→(2,2), (1,0)→(0,1), … Center (1,1) fixed.
Counter-clockwise
Transpose then reverse each column, or reverse rows then transpose. State the pair so you don’t flip the wrong way under pressure.
Anti-diagonal / 180°
180° = reverse rows then reverse each row (or two 90°). Quick follow-up answer.