Rotate Image
Medium · Math & Geometry · Explanation and code example
Reverse And Transpose
How it works
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.
Steps
- 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.
Complexity
- Time complexity:
O(n ^ 2) - Space complexity:
O(1)
Things to watch for
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.
Python code example
from typing import List
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]
C++ code example
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
// Reverse the matrix vertically
reverse(matrix.begin(), matrix.end());
// Transpose the matrix
for (int i = 0; i < matrix.size(); ++i) {
for (int j = i + 1; j < matrix[i].size(); ++j)
swap(matrix[i][j], matrix[j][i]);
}
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.