Skip to main content

48. Rotate Image

medium

Rotate an n x n matrix 90 degrees clockwise in-place. Tests the transpose-then-reverse trick — two clean O(1)-space passes beat a four-way rotation cycle.

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, which means you have to modify the input 2D matrix directly. Do not allocate another 2D matrix and do the rotation.

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]]

Example 3

Input
matrix = [[1]]
Output
[[1]]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Compare the original to the rotated. What two simple operations, applied in sequence, produce the same result?

Hint 2

Transpose (swap matrix[i][j] with matrix[j][i] for i < j) flips the matrix across its main diagonal. What's left?

Hint 3

After transposing, reverse each row. The combination of those two operations is exactly a 90-degree clockwise rotation.

Solution approach

Reveal approach

Transpose the matrix in place, then reverse each row. Transposition: for i in 0..n and j in i+1..n, swap matrix[i][j] with matrix[j][i]. This reflects the matrix across its main diagonal. Then for each row i, reverse matrix[i] (two-pointer swap from the ends inward). The composition transpose-then-reverse-rows is geometrically equivalent to a 90-degree clockwise rotation: transpose maps (i, j) to (j, i), and row-reversal maps (j, i) to (j, n-1-i), which is exactly where the original (i, j) belongs after a clockwise rotation. The alternative — rotating four cells at a time in a cycle — works but is fiddly with the index arithmetic.

Complexity

Time
O(n^2)
Space
O(1)

Related patterns

  • matrix
  • in-place
  • transpose

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Apple
  • Meta
  • Google

Practice these live with InterviewChamp.AI

Drill Rotate Image and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →