Skip to main content

13. Rotate Image

mediumAsked at Autodesk

Rotate an n x n matrix in place by 90 degrees clockwise.

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; do not allocate another matrix to perform the rotation.

Constraints

  • n == matrix.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=[[1,2],[3,4]]
Output
[[3,1],[4,2]]

Approaches

1. Copy to new matrix

Allocate a fresh n x n matrix and write rotated cells.

Time
O(n^2)
Space
O(n^2)
const r=Array.from({length:n},()=>Array(n));
for (let i=0;i<n;i++) for (let j=0;j<n;j++) r[j][n-1-i]=m[i][j];
copy back to m

Tradeoff:

2. Transpose + reverse rows

First mirror along the diagonal (transpose), then reverse each row. Two simple linear passes, no extra space.

Time
O(n^2)
Space
O(1)
function rotate(matrix) {
  const n = matrix.length;
  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]];
  for (const row of matrix) row.reverse();
}

Tradeoff:

Autodesk-specific tips

In-place matrix rotations parallel Autodesk's affine transforms applied to vertex buffers during raster image manipulation.

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

Practice these live with InterviewChamp.AI →