Rotate Image
On this page
Problem statement
Given an
n × nmatrix, rotate it 90 degrees clockwise in place. You must change the input matrix directly; allocating a secondn × nmatrix is not allowed.
A short problem that shows how carefully you handle indices. Interviewers like it because there is a neat two-step trick, and because the "obvious" in-place code has two classic bugs. Original problem: LeetCode 48.
Example

Input: [[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]
Output: [[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 11, 7, 3],
[16, 12, 8, 4]]
Input: [[7, 3],
[1, 9]]
Output: [[1, 7],
[9, 3]]
Constraints (assumed)
- 1 ≤ n ≤ 1,000.
- Values are integers (the type doesn't matter: only positions move).
What this question tests
- Working out where each cell goes:
m[i][j]moves tom[j][n − 1 − i]. - Doing it in place with O(1) extra memory, which rules out the copy-and-fill answer.
- Getting loop bounds right so each cell moves exactly once.
Questions to ask first
- Clockwise or counter-clockwise? (Here: clockwise.)
- Is the matrix always square? A non-square matrix can't be rotated in place because its shape changes. (Here: square.)
- Must it be in place, or may I return a new matrix? (Here: in place.)
- Is
npossibly 1 or odd? Odd sizes have a centre cell that never moves.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.