In-Place $90^\circ$ Clockwise Matrix Rotation: Transpose + Reverse
Rotating an $n \times n$ 2D matrix clockwise by $90^\circ$ requires moving each element at coordinate $(r, c)$ to the new coordinate $(c, n - 1 - r)$.
Allocating a secondary matrix makes this trivial in $O(n^2)$ extra memory. To perform the rotation completely in-place with $O(1)$ auxiliary space, we decompose the geometric rotation into two simple linear algebra transformations:
$$\text{Rotate } 90^\circ \text{ Clockwise} = \text{Transpose} \longrightarrow \text{Reverse Each Row}$$
Mathematical Intuition & Transformation Proof
-
Step 1: Matrix Transpose (Reflection across Main Diagonal) Swapping elements across the top-left to bottom-right diagonal maps each position: $$(r, c) \longrightarrow (c, r)$$
-
Step 2: Horizontal Reflection (Reverse Every Row) Flipping each row horizontally inverts the column coordinate while keeping row indices intact: $$(c, r) \longrightarrow (c, n - 1 - r)$$
This matches the exact coordinate mapping required for a $90^\circ$ clockwise rotation:
Original Matrix After Transpose (swap M[i][j], M[j][i]) After Row Reversal (flip columns)
1 2 3 1 4 7 7 4 1
4 5 6 ===> 2 5 8 ===> 8 5 2
7 8 9 3 6 9 9 6 3
(Note: To rotate $90^\circ$ counter-clockwise, invert the order: reverse each row first, then transpose—or transpose across the anti-diagonal).
Step-by-Step Execution Rules
- Transpose Loop Bounds: Iterate rows
ifrom0ton - 1, and columnsjstrictly fromi + 1ton - 1. Startingjati + 1ensures only the upper triangle is swapped with the lower triangle. Ifjstarted from0, elements would be swapped twice, reverting the matrix to its original state. - Row Reversal Bounds: For each row
i, run a standard two-pointer sweep whereleft = 0andright = n - 1, swapping elements until the pointers cross.
Implementation (C++ and Python)
C++ Implementation
#include <vector>
#include <algorithm>
void rotate(std::vector<std::vector<int>>& matrix) {
int n = matrix.size();
// Step 1: Transpose the matrix (reflect over main diagonal)
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
// Step 2: Reverse each row horizontally
for (int i = 0; i < n; ++i) {
int left = 0, right = n - 1;
while (left < right) {
std::swap(matrix[i][left], matrix[i][right]);
left++;
right--;
}
}
}
Python Implementation
def rotate(matrix: list[list[int]]) -> None:
"""
Rotates an n x n matrix 90 degrees clockwise in-place.
Modifies the input matrix directly without returning a new object.
"""
n = len(matrix)
# Step 1: Transpose the matrix in-place
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 & Memory Verification
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(n^2)$ | Transposing requires visiting $\frac{n(n - 1)}{2}$ cell pairs. Reversing all rows visits $\frac{n^2}{2}$ cell pairs. Total cell operations equal $n^2$, which is optimal because every cell must be repositioned. |
| Auxiliary Space | $O(1)$ | Swaps occur using a single temporary scalar variable in-place without heap allocations or cloning. |
Cache Locality & Hardware Efficiency
While cyclic 4-way rotation (4-cycle replacement) is another common $O(1)$ space technique, the Transpose + Reverse approach often exhibits superior execution speed in practice:
- Transposition and contiguous row reversals access memory in predictable sequential strides.
- Modern compiler vectorizers and CPU hardware prefetchers can vectorize the horizontal row reversals efficiently compared to non-contiguous 4-point cycle swaps.
