← Questions
Rotate a matrix by 90 degrees
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Apr 2026. It tests matrices and in-place.
Rotate an n × n integer matrix 90 degrees clockwise, in place. Don't allocate a second n × n matrix.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
rotate(matrix: list[list[int]]) -> None— modifiesmatrix. An empty matrix stays empty.
Example
[[1, 2, 3], [[7, 4, 1],
[4, 5, 6], -> [8, 5, 2],
[7, 8, 9]] [9, 6, 3]]
[[ 5, 1, 9, 11], [[15, 13, 2, 5],
[ 2, 4, 8, 10], -> [14, 3, 4, 1],
[13, 3, 6, 7], [12, 6, 8, 9],
[15, 14, 12, 16]] [16, 7, 10, 11]]
Constraints
-
0 <= n <= 200; the matrix is square.
Clarifying questions
- Clockwise or counter-clockwise?
- Must it be in place, or may I return a new matrix?
- Is the matrix always square?
What a strong answer covers
- Transpose (swap only above the diagonal), then reverse each row; or rotate four cells at a time, layer by layer.
- Index arithmetic for the layer approach, done carefully.
- O(n²) time, O(1) extra space.
- Tests: 0×0, 1×1, 2×2, odd and even
n.
Follow-ups
- Counter-clockwise, or 180 degrees.
- A rectangular
m × nmatrix: why in place no longer works directly. - Rotate by
kquarter turns.
Where it's asked
- Amazon · Coding · Last asked Apr 202655 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
matrices · in-place
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
