Rotate Image
Difficulty: Medium
You're given an n x n matrix representing an image. Rotate it 90 degrees clockwise.
Do it in place: modify the given grid directly instead of returning a new one.
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
The first column, read bottom to top (7, 4, 1), becomes the new first row. The second column, read bottom to top (8, 5, 2), becomes the new second row, and so on.
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Input: matrix = [[5]]
Output: [[5]]
A single cell has nothing to rotate around.
Constraints
n == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
Approach
The easiest way is to work out where each cell lands after rotation and place it there in a new grid. That's simple, but uses extra memory the size of the whole grid.
To do it in place, split the rotation into two steps. First transpose the matrix: flip it across its main diagonal, so matrix[r][c] and matrix[c][r] swap. Then reverse every row. Together, in that order, they equal a 90-degree clockwise rotation, with no extra grid.
Solutions
Brute Force - Build a New Rotated Grid
After a 90-degree clockwise rotation, the cell at row r, column c ends up at row c, column (n - 1 - r). Build a new grid by placing each cell there, then copy it back over the original.
function rotate(matrix) {
const n = matrix.length;
const rotated = Array.from({ length: n }, () => new Array(n).fill(0));
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
rotated[c][n - 1 - r] = matrix[r][c];
}
}
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
matrix[r][c] = rotated[r][c];
}
}
}Time: O(n²) · Space: O(n²)
Optimal - Transpose, Then Reverse Rows
Transpose the grid in place by swapping matrix[r][c] with matrix[c][r] for every pair above the main diagonal. Then reverse each row. These two in-place steps give a 90-degree clockwise rotation with no extra grid.
function rotate(matrix) {
const n = matrix.length;
// Transpose: flip across the main diagonal
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
[matrix[r][c], matrix[c][r]] = [matrix[c][r], matrix[r][c]];
}
}
// Reverse each row
for (let r = 0; r < n; r++) {
matrix[r].reverse();
}
}Time: O(n²) · Space: O(1) extra space