48. Rotate Image
At a Glance
- Topic: arrays-hashing
- Pattern: Transpose + reverse rows (90° clockwise)
- Difficulty: Medium
- Companies: Amazon, Google, Meta, Microsoft, Apple
- Frequency: High
- LeetCode: 48
Problem (one-liner)
Given an n × n matrix grid, rotate the image 90 degrees clockwise in-place.
Recognition Cues
- "Rotate image 90° clockwise", "in-place"
- Transpose across main diagonal, then reverse each row — or reverse columns then transpose for CCW
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — copy to new matrix with mapping
(row,col) -> (col, n-1-row)—O(n²)space. - Better — rotate four cells at a time layer by layer —
O(1)extra. - Optimal — transpose + reverse each row —
O(n²)time /O(1)extra — simple to code.
Optimal Solution
Go
package main
func rotate(grid [][]int) {
length := len(grid)
for row := 0; row < length; row++ {
for col := row + 1; col < length; col++ {
grid[row][col], grid[col][row] = grid[col][row], grid[row][col]
}
}
for row := 0; row < length; row++ {
left := 0
right := length - 1
for left < right {
grid[row][left], grid[row][right] = grid[row][right], grid[row][left]
left++
right--
}
}
}JavaScript
function rotate(grid) {
const length = grid.length;
for (let row = 0; row < length; row++) {
for (let col = row + 1; col < length; col++) {
[grid[row][col], grid[col][row]] = [grid[col][row], grid[row][col]];
}
}
for (let row = 0; row < length; row++) {
let left = 0;
let right = length - 1;
while (left < right) {
[grid[row][left], grid[row][right]] = [grid[row][right], grid[row][left]];
left++;
right--;
}
}
}Walkthrough
grid = [[1,2,3],[4,5,6],[7,8,9]]
| phase | matrix state |
|---|---|
| initial | 1 2 3 / 4 5 6 / 7 8 9 |
| after transpose | 1 4 7 / 2 5 8 / 3 6 9 |
| reverse row 0 | 7 4 1 / 2 5 8 / 3 6 9 |
| reverse row 1 | 7 4 1 / 8 5 2 / 3 6 9 |
| reverse row 2 | 7 4 1 / 8 5 2 / 9 6 3 |
Final clockwise 90° layout achieved.
Edge Cases
n = 1— no-op.- Even vs odd
n— same algorithm.
Pitfalls
- Mixing transpose indices — only swap
col > rowto avoid double swap. - Counter-clockwise rotation uses different pair of operations.
Similar Problems
- 054. Spiral Matrix — boundary traversal.
- 189. Rotate Array — 1D rotation analogue.
- 036. Valid Sudoku — grid indexing.
Variants
- Rotate by 180° — double apply or reverse all rows then columns.
- Rectangular matrix — four-way cycle rotation.
Mind-Map Tags
#matrix #transpose #reverse #in-place #geometry
Last updated on
Spotted something unclear or wrong on this page?