Rotate Image
Rotate Image is LeetCode 48 (Medium). You get an n × n matrix of numbers (the image) and must turn it 90 degrees clockwise in place: change the given matrix, without allocating a second one.
nis between 1 and 20, so the matrix is always square.- After the turn, the first row holds what was the first column, read from bottom to top.
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
Intuition
A clockwise turn sends the value at row i, column j to row j, column n − 1 − i. That move is hard to do directly without overwriting values, but it splits into two moves that are each made of simple swaps.
- Transpose: swap across the main diagonal, so
(i, j)goes to(j, i). Rows become columns. - Reverse each row:
(j, i)goes to(j, n − 1 − i). Each row is flipped left to right.
Together they take (i, j) to (j, n − 1 − i): to rotate a matrix 90 degrees clockwise, transpose it and then reverse every row. Both moves only swap pairs of cells, so no value is ever lost and no second matrix is needed.
"Rotate a square grid in place" usually breaks into two mirror flips (transpose plus a row or column reversal), each made of plain pair swaps.
Approach
Before reading on, take a 3 × 3 grid numbered 1 to 9 row by row and write its rotated form. Then find which simple flip of the grid gets you halfway there, and which second flip finishes it.
Two ways to turn the matrix
Two passes of plain pair swaps.
- Hard to get wrong: each pass has one simple index rule.
- Easy to adapt: other turns are a different pair of flips.
The version to write in an interview.
Moves four cells at once, one from each side of a square ring.
- One pass: every value is written once.
- Index-heavy: four expressions with
n − 1 − ithat must all be right.
Worth knowing; easy to slip on.
Both are in place and touch every cell a constant number of times. The two-flip version is traced below; the cycle version follows the demo.
Transpose across the main diagonal
For each row i, swap matrix[i][j] with matrix[j][i] for every column j > i. Only the cells above the diagonal start a swap, so each pair is exchanged exactly once; the diagonal cells stay put.
Reverse every row
Flip each row end to end, swapping its first and last entries, then the next pair inward. After the transpose a row holds an old column top to bottom; reversing it puts that column bottom to top, which is what a clockwise turn needs.
Code in Python, C++ and Java
Four-cell cycles, ring by ring
Peel the matrix into square rings from the outside in; ring i runs from index i to n − 1 − i. A clockwise turn moves each cell of a ring one side over, and four cells, one on each side, form a closed cycle: left → top → right → bottom → left. Save the top cell, fill each position from the cell that rotates into it, and drop the saved value into the right side. For odd n the centre cell is never touched.
Common pitfalls
Transposing over the whole matrix
for i in range(n):
for j in range(n):
swap(i, j)for i in range(n):
for j in range(i + 1, n):
swap(i, j)With j starting at 0, every pair is swapped twice, once from each side of the diagonal, and the second swap undoes the first. The transpose leaves [[1, 2], [3, 4]] unchanged, so the result is just each row reversed: [[2, 1], [4, 3]] instead of [[3, 1], [4, 2]].
Reversing the wrong direction
transpose reverse the order of the rows
transpose reverse each row
Reversing the list of rows after a transpose turns the matrix counterclockwise. [[1, 2], [3, 4]] becomes [[2, 4], [1, 3]] instead of [[3, 1], [4, 2]].
Building a rotated copy
matrix = [list(r) for r in zip(*matrix[::-1])]
matrix[:] = [list(r) for r in zip(*matrix[::-1])] # or the in-place swaps
Assigning to the name matrix only changes the local variable; the caller's grid is untouched and the judge sees the original. Writing through matrix[:] fixes that, but it still builds a full second matrix, which the problem rules out.
Edge cases
No pair lies above the diagonal and the single row has nothing to swap, so the matrix is left as it is, which is correct.
The centre cell sits on the diagonal and in the middle of its row, so neither pass moves it, matching a real rotation where the centre stays fixed.
Complexity
n(n − 1) / 2 swaps and the row reversals about n² / 2 more, so every cell is touched at most twice. Only loop indices and one temporary value are stored.Rotate Image FAQ
How do you rotate a matrix 90 degrees counterclockwise?
Transpose, then reverse the order of the rows (flip top to bottom) instead of reversing each row. Equivalently, reverse each row first and then transpose.
What about 180 degrees?
Reverse the order of the rows and reverse each row. No transpose is needed, and the result is the same as rotating 90 degrees twice.
Does this work for a rectangular matrix?
Not in place. Rotating an m × n grid gives an n × m grid, which has a different shape, so a new matrix has to be built: entry (i, j) of the result is old[m − 1 − j][i].