Rotate Image
Problem
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
[[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]def rotate(matrix):
n = len(matrix)
for r in range(n):
for c in range(r + 1, n):
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
for r in range(n):
matrix[r].reverse()
function rotate(matrix) {
const n = matrix.length;
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
const t = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = t;
}
}
for (let r = 0; r < n; r++) {
matrix[r].reverse();
}
}
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int r = 0; r < n; r++) {
for (int c = r + 1; c < n; c++) {
int t = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = t;
}
}
for (int r = 0; r < n; r++) {
for (int i = 0, j = n - 1; i < j; i++, j--) {
int t = matrix[r][i];
matrix[r][i] = matrix[r][j];
matrix[r][j] = t;
}
}
}
}
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int r = 0; r < n; ++r) {
for (int c = r + 1; c < n; ++c) {
swap(matrix[r][c], matrix[c][r]);
}
}
for (int r = 0; r < n; ++r) {
reverse(matrix[r].begin(), matrix[r].end());
}
}
Explanation
Rotating a square matrix 90° clockwise in place looks tricky, but it splits into two easy moves: transpose the matrix, then reverse each row.
Transposing means swapping matrix[r][c] with matrix[c][r] — it flips the grid across its main diagonal so rows become columns. We only loop the inner column from c = r + 1 so each pair is swapped once and the diagonal is left alone.
After the transpose, the numbers are in the right columns but each row is left-to-right backwards compared to a clockwise turn. Reversing every row fixes that and completes the rotation. Both steps modify the original grid directly, so no second matrix is needed.
Example: [[1,2,3],[4,5,6],[7,8,9]]. Transpose gives [[1,4,7],[2,5,8],[3,6,9]]. Reversing each row gives [[7,4,1],[8,5,2],[9,6,3]] — exactly a 90° clockwise rotation.
We touch each of the n² cells a constant number of times, so it runs in O(n²) with only constant extra space.