Skip to main content

19. Rotate Image

mediumAsked at Wix

Rotate an n×n matrix 90 degrees in place — Wix asks this to test spatial matrix reasoning, which maps directly to 2-D grid layout transforms and canvas rotation operations in the site editor.

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. You must rotate the matrix in place without allocating 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. Extra matrix

Allocate a new matrix and place element [r][c] at position [c][n-1-r] in the new matrix.

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

Transpose the matrix (swap across the main diagonal), then reverse each row. Two O(n^2) passes with O(1) extra space.

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

Tradeoff:

Wix-specific tips

Wix expects you to derive the transpose + reverse-rows identity rather than memorise it — walk through a 2×2 example on the whiteboard to prove the decomposition. That rigour signals the kind of spatial reasoning their rendering and canvas teams prize.

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

Practice these live with InterviewChamp.AI →