48. Rotate Image
mediumRotate 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 Sam K., 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].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]Example 2
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]][[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]Example 3
matrix = [[1]][[1]]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
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
More Arrays practice problems
- 1. Two Sum
- 11. Container With Most Water
- 15. 3Sum
- 26. Remove Duplicates from Sorted Array
- 31. Next Permutation
- 41. First Missing Positive
- 53. Maximum Subarray
- 54. Spiral Matrix