Skip to main content

48. Rotate Image

mediumAsked at Ola

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

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 have to rotate the image 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. Copy into new matrix

Allocate an n x n result and write [i][j] = old[n-1-j][i].

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

Tradeoff:

2. Transpose then reverse rows

Swap matrix[i][j] with matrix[j][i] for i<j, then reverse each row.

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:

Ola-specific tips

Ola interviewers value the transpose-then-reverse trick; tie it to rotating a city-zone heatmap before rendering on a new device-orientation.

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

Practice these live with InterviewChamp.AI →