Skip to main content

48. Rotate Image

mediumAsked at Canva

Rotate an n×n matrix 90 degrees clockwise in-place — Canva reaches for this to see whether you can decompose a 2D coordinate transform into the transpose-then-reflect steps their canvas rotation engine uses under the hood.

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. You must modify the input matrix directly without allocating another 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]]

Explanation: Rotating 90° clockwise: column 0 becomes row 0 in reverse, etc.

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)

Copy each element to its rotated position in a new matrix, then overwrite the original.

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. Optimal (transpose then reverse rows)

Transpose the matrix along the main diagonal, then reverse each row — achieves 90° clockwise rotation in-place with no 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:

Canva-specific tips

Canva's canvas engine performs affine transforms — rotation, scaling, skewing — on element bounding boxes. Interviewers want to see you decompose the rotation into two atomic steps (transpose + row-reverse) rather than calculating target coordinates ad hoc. Talk through why the transpose step works geometrically: element at (i, j) maps to (j, i), then reversing rows maps (j, i) to (j, n-1-i), which is exactly the 90° clockwise destination. Verify your logic on the 3×3 example by hand before coding.

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

Practice these live with InterviewChamp.AI →