Rotate Image
Problem
You are given an
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.
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.
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]]
Key Insight
90° clockwise rotation = transpose + reverse each row.
90° clockwise = Transpose + Reverse each row. Transpose swaps (i,j)<->(j,i). Both operations are in-place.
How to Approach This Problem
Pattern Recognition: When you see keywords like
rotate image math-and-geometry,
think Math & Geometry.
Step-by-Step Reasoning
1
Transposing a matrix:
Answer: Swaps rows and columns
Element at (i,j) goes to (j,i).
2
After 90° clockwise, element at (i, j) goes to:
Answer: (j, n-1-i)
Row i becomes column n-1-i. Column j becomes row j.
3
90° clockwise rotation equals:
Answer: Transpose + reverse rows
Transpose swaps (i,j)->(j,i). Reversing rows of transpose gives 90° clockwise.
4
In-place transpose swaps:
Answer: matrix[i][j] with matrix[j][i]
Only swap upper triangle with lower triangle.
5
For in-place transpose, we iterate:
Answer: Only upper triangle (j > i)
Swapping all would swap twice (back to original). Only swap where j > i.
Solution
def rotate(matrix: List[List[int]]) -> None:
n = len(matrix)
# Step 1: Transpose (swap across diagonal)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Step 2: Reverse each row
for i in range(n):
matrix[i].reverse()
Complexity Analysis
| Time | O(n²) |
|---|---|
| Space | O(1) |
Master This Pattern
Build intuition with interactive MCQs. Practice Math & Geometry problems in the LeetEye app.
Download LeetEye Free