Rotate an image 90°
Medium TimeO(n²) SpaceO(1)
Given an n × n matrix, turn it 90° clockwise in place, with no second matrix of the same size, so [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. The top row ends up as the right-hand column, and every value has to land where the rotation puts it rather than merely somewhere plausible.
Examples
Example 1
- Input
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Output
- The top row
[[7,4,1],[8,5,2],[9,6,3]]1, 2, 3is now the right-hand column, read downwards.
Example 2
- Input
- matrix = [[1, 2], [3, 4]]
- Output
- The top row
[[3,1],[4,2]]1, 2becomes the right-hand column, and an even size leaves no centre cell.
The Code
function rotate(matrix) {
const n = matrix.length;
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
const temp = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = temp;
}
}
for (let r = 0; r < n; r++) {
matrix[r].reverse();
}
return matrix;
}
rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);Done
More like this
All matrices & grids examples (7) →- Spiral order Four shrinking boundaries peel the grid one ring at a time.
- Transpose Rows become columns — read down instead of across.
- Flood fill The paint-bucket tool — recurse outwards while the colour matches.
- Count islands Every unvisited land cell starts an island — then sink the rest.
- Set matrix zeroes Record which rows and columns to blank before blanking anything.
- Maximal rectangle Every row is a histogram — solve that, then sweep downwards.