Rotate Image
Difficulty: Medium · Pattern: Matrix · LeetCode #48
Rotate an n × n matrix 90° clockwise in place. Don't allocate another matrix.
Examples
text
[[1,2,3], [[7,4,1],
[4,5,6], → [8,5,2],
[7,8,9]] [9,6,3]]Hints
- Where does the element at
(r, c)end up? At(c, n−1−r). - That mapping is the composition of two easy in-place operations.
Approach
Transpose + reverse rows: transposing maps (r,c) → (c,r), and reversing each row maps (c,r) → (c, n−1−r). Together that's exactly the 90° clockwise rotation. Both steps are in-place swaps.
Other rotations follow the same idea:
- Counter-clockwise: transpose + reverse each column, or reverse rows then transpose.
- 180°: reverse the rows and reverse each row.
The alternative "rotate four cells at a time, layer by layer" also works, but it's easier to get the indices wrong.
Complexity
Time: O(n²). Space: O(1).
Python solution
def rotate(matrix):
n = len(matrix)
for r in range(n):
for c in range(r + 1, n):
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
for row in matrix:
row.reverse()JavaScript solution
function rotate(matrix) {
const n = matrix.length;
// layer-by-layer 4-way swap
for (let layer = 0; layer < n >> 1; layer++) {
const first = layer, last = n - 1 - layer;
for (let i = first; i < last; i++) {
const off = i - first, top = matrix[first][i];
matrix[first][i] = matrix[last - off][first];
matrix[last - off][first] = matrix[last][last - off];
matrix[last][last - off] = matrix[i][last];
matrix[i][last] = top;
}
}
}