← Questions
Rotate an image matrix 90 degrees in place
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Apr 2026. It tests matrices and arrays.
An image is stored as an n x n matrix of pixels. Rotate it 90 degrees clockwise in place, without allocating a second matrix.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
rotate(matrix: list[list[int]]) -> None— rotatesmatrixclockwise by 90 degrees, modifying it in place.
Example
[[1, 2, 3], [[7, 4, 1],
[4, 5, 6], -> [8, 5, 2],
[7, 8, 9]] [9, 6, 3]]
The first row becomes the last column; cell (i, j) moves to (j, n-1-i).
Constraints
-
1 <= n <= 1000; the matrix is square. - Use
O(1)extra memory.
Clarifying questions
- Clockwise or counterclockwise?
- Is the matrix always square?
- Must it be in place, or may I return a new matrix?
What a strong answer covers
- Transpose (swap
(i, j)with(j, i)forj > i), then reverse each row; or rotate the four cells of each ring in one cycle,n/2rings deep. -
O(n²)time andO(1)extra space; why a copy-based version is simpler but costsO(n²)memory. - The index arithmetic for the ring rotation, and the middle cell of an odd
n. - Tests:
1 x 1,2 x 2, an odd and an even size, and rotating four times returns the original.
Follow-ups
- Rotate counterclockwise, or by 180 degrees.
- Rotate a non-square
m x nimage: why it can no longer be done in place in the same buffer. - The image is too large for memory and stored in tiles: how would you rotate it?
Where it's asked
- Apple · Technical phone screen · Last asked Apr 2026
What it tests
matrices · arrays
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
