Approach Summary
Two-step in-place: first transpose (swap [i][j] and [j][i]), then mirror horizontally (reverse each row).
Full Solution & Approach
Rotating a square matrix 90 degrees clockwise can be decomposed into two simple in-place operations: transpose, then reverse each row. Transposing swaps matrix[i][j] with matrix[j][i] for all i < j — after this, rows and columns have traded places. Reversing every row then produces the exact clockwise rotation. The two-step view is the mental model interviewers look for, and it avoids the error-prone four-way element rotation. A direct four-way rotation also works: for each layer (ring) of the square, rotate the four corners and the intermediate positions cyclically — this is faster in one pass but much easier to get wrong with off-by-one errors at the layer boundaries. The transpose-then-reverse version operates on every element exactly twice with trivial indexing, so it is both correct and simple to explain. For a counter-clockwise rotation the same trick applies with the steps swapped: transpose followed by reversing each column, or equivalently reverse each row first then transpose.
Both steps visit every cell a constant number of times — O(n²) time for an n×n matrix. All operations are swaps in place, so O(1) extra space.
Solution Code
Solution
def rotate(matrix: list[list[int]]) -> None:
n = len(matrix)
# Transpose: swap across the main 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]
# Reverse each row
for row in matrix:
row.reverse()function rotate(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) matrix[i].reverse();
}public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for (int i = 0; i < n; i++) {
int lo = 0, hi = n - 1;
while (lo < hi) {
int tmp = matrix[i][lo];
matrix[i][lo] = matrix[i][hi];
matrix[i][hi] = tmp;
lo++; hi--;
}
}
}void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
swap(matrix[i][j], matrix[j][i]);
for (auto& row : matrix)
reverse(row.begin(), row.end());
} Edge Cases to Watch
- 1×1 matrix — no rotation actually changes it
- Odd-dimension matrix — the center cell is untouched
- Repeated values — the rotation still applies cell-by-cell
- The matrix must be modified in place — the method returns nothing
How to Recognize This Pattern
- Rotate matrix 90° clockwise in-place
- Transpose + mirror
Complexity Analysis
Time Complexity
O(n²)
Space Complexity
O(1)