← Questions

Rotate an image matrix 90 degrees in place

0
AppleCodingLast asked Apr 2026

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 — rotates matrix clockwise 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) for j > i), then reverse each row; or rotate the four cells of each ring in one cycle, n/2 rings deep.
  • O(n²) time and O(1) extra space; why a copy-based version is simpler but costs O(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 n image: 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

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