Rotate Image
Rotate an n×n matrix 90° clockwise in place. Transpose it (swap across the main diagonal), then reverse every row. The two reflections together are a rotation.
▶ Watch the animated traceTraced input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] → [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. Original problem: neetcode.io/problems/rotate-matrix
Complexity
BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceO(1)
Each cell is swapped a constant number of times.
Key idea
- Clockwise rotation = transpose, then mirror left-right.
- Transpose only swaps cells above the diagonal (j > i), or it undoes itself.
- Counter-clockwise would reverse columns instead of rows.
Common mistakes
- Transposing the whole matrix (j from 0) swaps everything twice.
- Using a second matrix breaks the in-place requirement.
Solution
Java
void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int t = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = t;
}
for (int[] row : matrix) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int t = row[l];
row[l] = row[r];
row[r] = t;
}
}
}Python
def rotate(matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()C++
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
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| 1×1 Unchanged. | matrix = [[1]] | [[1]] |
| 2×2 One swap, then two row reversals. | matrix = [[1, 2], [3, 4]] | [[3, 1], [4, 2]] |