Skip to main content

17. Rotate Image

mediumAsked at Tesla

Rotate an n×n matrix 90 degrees in-place — Tesla's vision pipeline applies this exact transformation when fusing camera frames from different sensor orientations into a unified bird's-eye-view grid for Autopilot.

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

Problem

You are given an n×n 2D matrix representing an image. Rotate the matrix 90 degrees clockwise in-place without allocating a new matrix.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000
  • Must be done in-place with 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]]

Explanation: Transpose then reverse each row achieves a 90-degree clockwise rotation.

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

Allocate a new n×n matrix, compute the rotated index mapping directly, then copy back. Clean but uses O(n^2) extra space.

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

Tradeoff:

2. Transpose then reverse rows

First transpose the matrix (swap matrix[i][j] with matrix[j][i]), then reverse each row in-place. Two clean passes, O(1) 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:

Tesla-specific tips

Tesla asks this to test spatial reasoning, which maps directly to how engineers think about camera-to-BEV coordinate transforms. They want to hear you derive the transpose-then-reverse trick rather than recall it — walk through a 2×2 example live to prove you understand the math. Also discuss how in real sensor pipelines you'd compose multiple rotations as matrix multiplications to avoid multiple passes.

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 Tesla interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →