Rotate a square matrix 90 degrees clockwise in place.
Start with the concrete trace below. It shows the state the algorithm must carry as it runs.
Problem trace
Rotate Image: Reverse row order, then swap every above-diagonal cell with its reflected below-diagonal partner.
- Recognize it
- Use this transformation for a square matrix that must rotate 90 degrees clockwise without allocating a second matrix.
- Keep true
- After row reversal, values have moved from (r,c) to (n-1-r,c); after transposition, each reaches (c,n-1-r), exactly its clockwise coordinate.
- Reuse it
- Derive a target coordinate mapping, then factor it into simple reversible transforms whose in-place loops visit each swap pair exactly once.
Pattern: Reverse rows, then transpose.
Simple idea: Reversing row order moves the bottom to the top. Swapping across the main diagonal then puts every value in its clockwise position.
def rotate_image(matrix: list[list[int]]) -> None:
matrix.reverse()
for row in range(len(matrix)):
for col in range(row + 1, len(matrix)):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
Cost: time and space.