48. Rotate Image - Explanation
Description
Given a square n x n matrix of integers matrix, rotate it by 90 degrees clockwise.
You must rotate the matrix in-place. Do not allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [
[1,2],
[3,4]
]
Output: [
[3,1],
[4,2]
]Example 2:
Input: matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
Output: [
[7,4,1],
[8,5,2],
[9,6,3]
]Constraints:
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(n^2) time and O(1) space, where n is the length of the side of the given square matrix.
Hint 1
A brute force approach would use O(n^2) extra space to solve the problem. Can you think of a way to avoid using extra space? Maybe you should consider observing the positions of the elements before rotating and after rotating of the matrix.
Hint 2
We can rotate the matrix in two steps. First, we reverse the matrix vertically, meaning the first row becomes the last, the second row becomes the second last, and so on. Next, we transpose the reversed matrix, meaning rows become columns and columns become rows. How would you transpose the matrix?
Hint 3
Since the given matrix is a square matrix, we only need to iterate over the upper triangular part, meaning the right upper portion of the main diagonal. In this way, we can transpose a matrix.
Prerequisites
Before attempting this problem, you should be comfortable with:
- 2D Array Indexing - Understanding how to access and modify elements using row and column indices
- Matrix Transpose - Swapping elements across the main diagonal where element (i,j) swaps with (j,i)
- In-Place Manipulation - Rotating elements within the matrix without using additional space for a copy
- Layer-by-Layer Processing - Processing a matrix from outer boundaries inward, handling four elements at a time
1. Brute Force
Intuition
We are given an n x n matrix and need to rotate it 90 degrees clockwise.
A direct and beginner-friendly way to think about this is:
- create a new matrix where each element from the original matrix is placed in its rotated position
- after building this rotated version, copy it back into the original matrix
The key observation for a 90° clockwise rotation is:
- an element at position
(i, j)in the originalmatrix - moves to position
(j, n - 1 - i)in the rotatedmatrix
By applying this rule to every cell, we can construct the rotated matrix easily.
Algorithm
- Let
nbe the size of thematrix. - Create a new
n x nmatrixcalledrotated, initially filled with zeros. - Traverse each cell
(i, j)of the originalmatrix:- place its value into the rotated position:
rotated[j][n - 1 - i] = matrix[i][j]
- place its value into the rotated position:
- After filling the
rotatedmatrix, copy all values back into the originalmatrix. - The original
matrixis now rotated 90 degrees clockwise.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
rotated = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - 1 - i] = matrix[i][j]
for i in range(n):
for j in range(n):
matrix[i][j] = rotated[i][j]Time & Space Complexity
- Time complexity:
- Space complexity:
2. Rotate By Four Cells
Intuition
We want to rotate an n x n matrix 90 degrees clockwise, but this time in-place, without using extra space.
A useful way to visualize this is to rotate the matrix layer by layer, starting from the outermost layer and moving inward.
For each square layer:
- elements move in groups of four
- each element in the group shifts to its new rotated position
Specifically, for a given layer:
top-left→top-righttop-right→bottom-rightbottom-right→bottom-leftbottom-left→top-left
By rotating these four cells at a time, we complete the rotation without needing an extra matrix.
Algorithm
- Initialize two pointers:
l = 0→ left boundary of the current layerr = n - 1→ right boundary of the current layer
- While
l < r(process each layer): - For each position
iin the current layer (from0tor - l - 1):- Identify:
top = lbottom = r
- Save the
top-leftvalue temporarily - Move
bottom-left→top-left - Move
bottom-right→bottom-left - Move
top-right→bottom-right - Move saved
top-left→top-right
- Identify:
- After finishing one layer:
- increment
l - decrement
r
- increment
- Continue until all layers are rotated.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
l, r = 0, len(matrix) - 1
while l < r:
for i in range(r - l):
top, bottom = l, r
# save the topleft
topLeft = matrix[top][l + i]
# move bottom left into top left
matrix[top][l + i] = matrix[bottom - i][l]
# move bottom right into bottom left
matrix[bottom - i][l] = matrix[bottom][r - i]
# move top right into bottom right
matrix[bottom][r - i] = matrix[top + i][r]
# move top left into top right
matrix[top + i][r] = topLeft
r -= 1
l += 1Time & Space Complexity
- Time complexity:
- Space complexity:
3. Reverse And Transpose
Intuition
We want to rotate an n x n matrix 90 degrees clockwise in-place.
A very clean way to do this is to break the rotation into two simple operations:
- Reverse the
matrixvertically - Transpose the
matrix
Why this works:
- Reversing the
matrixflips it upside down - Transposing swaps rows with columns
- Doing both together results in a 90° clockwise rotation
This method is elegant, easy to remember, and avoids extra space.
Algorithm
- Reverse the
matrixvertically:- the first row becomes the last
- the last row becomes the first
- Transpose the
matrix:- swap elements across the main diagonal
- for all
i < j, swapmatrix[i][j]withmatrix[j][i]
- The
matrixis now rotated 90 degrees clockwise in-place.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
# Reverse the matrix vertically
matrix.reverse()
# Transpose the matrix
for i in range(len(matrix)):
for j in range(i + 1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Confusing Clockwise and Counter-Clockwise Rotation
The order of operations matters: for 90-degree clockwise rotation, reverse rows first then transpose. For counter-clockwise, transpose first then reverse rows. Mixing up this order or using the wrong sequence produces incorrect rotations.
Transposing the Entire Matrix Instead of Upper Triangle
When transposing in-place, swapping all pairs (i, j) with (j, i) including when i > j swaps each element twice, returning to the original matrix. The inner loop should only iterate for j > i to swap each pair exactly once.
Incorrect Index Calculation in Layer-by-Layer Rotation
In the four-cell rotation approach, computing the indices for the four corners incorrectly causes elements to be placed in wrong positions. Each of the four positions involves different combinations of l, r, i, top, and bottom, and confusing these leads to corrupted matrix values.
Sign in to join the discussion