Skip to main content

48. Rotate Image

mediumAsked at Snap

Snap's camera pipeline rotates raw sensor frames in-place before applying AR filters — knowing how to transpose and reflect a matrix without allocating extra memory maps directly to that constraint.

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

Problem

Given an n x n 2D matrix representing an image, rotate it 90 degrees clockwise in-place. You must not allocate another 2D matrix.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

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. Brute force (extra matrix)

Allocate a copy, map each (i,j) to (j, n-1-i) in the original. O(n^2) space.

Time
O(n^2)
Space
O(n^2)
function rotateImage(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

Step 1: transpose (swap matrix[i][j] with matrix[j][i]). Step 2: reverse each row. Two linear-time passes, O(1) extra space. This is the pattern Snap's camera service uses to avoid a buffer alloc on every incoming frame.

Time
O(n^2)
Space
O(1)
function rotateImage(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:

Snap-specific tips

Snap interviewers watch whether you reach for transpose+reverse or four-way cycle swap — either is acceptable, but they want you to articulate why you chose one. Mention sensor frame buffers to show domain awareness.

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

Practice these live with InterviewChamp.AI →