Skip to main content

30. Rotate Image

mediumAsked at Apple

Rotate an n×n matrix 90 degrees clockwise in-place — Apple's AVFoundation and Photos frameworks rotate CVPixelBuffer image data without allocating extra memory on memory-constrained iPhones, making this in-place matrix transformation a consistent favorite for Camera and Vision team interviews.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise) in-place. You must rotate the matrix in-place, modifying the input matrix directly. Do not allocate another 2D matrix.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000
  • Must be in-place — O(1) extra space

Examples

Example 1

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]

Example 2

Input
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output
[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Approaches

1. Extra matrix copy

Copy to a new matrix placing element [i][j] at [j][n-1-i]. Violates the in-place constraint but useful to verify correctness.

Time
O(n^2)
Space
O(n^2)
function rotate(matrix) {
  const n = matrix.length;
  const copy = matrix.map(row => [...row]);
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      matrix[j][n - 1 - i] = copy[i][j];
    }
  }
}

Tradeoff:

2. Transpose then reverse rows (in-place)

Step 1: Transpose matrix (swap [i][j] with [j][i]). Step 2: Reverse each row. Two simple passes, zero extra space.

Time
O(n^2)
Space
O(1)
function rotate(matrix) {
  const n = matrix.length;
  // Step 1: Transpose
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
  }
  // Step 2: Reverse each row
  for (let i = 0; i < n; i++) {
    matrix[i].reverse();
  }
}

Tradeoff:

Apple-specific tips

Apple's AVFoundation and Photos libraries rotate CVPixelBuffers in-place for camera preview and export — interviewers from those teams appreciate when you mention the memory-budget motivation behind the in-place constraint. The transpose-then-reverse trick is elegant and easy to verify on a 3×3 example; always sketch the 3×3 case on the whiteboard first to build confidence and show systematic thinking. For counter-clockwise rotation, reverse rows first then transpose — mention this extension to show you internalized the geometric reasoning, not just memorized the steps.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Rotate Image and other Apple interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →