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
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.
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.
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?
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.
Before attempting this problem, you should be comfortable with:
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:
The key observation for a 90° clockwise rotation is:
(i, j) in the original matrix(j, n - 1 - i) in the rotated matrixBy applying this rule to every cell, we can construct the rotated matrix easily.
n be the size of the matrix.n x n matrix called rotated, initially filled with zeros.(i, j) of the original matrix:rotated[j][n - 1 - i] = matrix[i][j]rotated matrix, copy all values back into the original matrix.matrix is 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]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:
Specifically, for a given layer:
top-left → top-righttop-right → bottom-rightbottom-right → bottom-leftbottom-left → top-leftBy rotating these four cells at a time, we complete the rotation without needing an extra matrix.
l = 0 → left boundary of the current layerr = n - 1 → right boundary of the current layerl < r (process each layer):i in the current layer (from 0 to r - l - 1):top = lbottom = rtop-left value temporarilybottom-left → top-leftbottom-right → bottom-lefttop-right → bottom-righttop-left → top-rightlrclass 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 += 1We 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:
matrix verticallymatrixWhy this works:
matrix flips it upside downThis method is elegant, easy to remember, and avoids extra space.
matrix vertically:matrix:i < j, swap matrix[i][j] with matrix[j][i]matrix is now rotated 90 degrees clockwise in-place.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.
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.
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.