Overview
Given an n × n 2D matrix, rotate it 90 degrees clockwise in-place.
Constraints
1 <= n <= 20-1000 <= matrix[i][j] <= 1000- Modify the matrix in place — do not allocate another 2D matrix.
Examples
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; rotate(matrix); // matrix is now: // [[7, 4, 1], // [8, 5, 2], // [9, 6, 3]]
const matrix = [ [1, 2], [3, 4] ]; rotate(matrix); // [[3, 1], // [4, 2]]
Solution
Reveal solution
function rotate(matrix) {
const n = matrix.length;
// Transpose
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]];
}
}
// Reverse each row
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
return matrix;
}Transpose the matrix (swap across the diagonal), then reverse each row. Both operations together yield a 90° clockwise rotation.
Resources
matrix-rotation.js
Matrix Rotation
mediumcodingAlgorithmsMatrix
Overview
Given an n × n 2D matrix, rotate it 90 degrees clockwise in-place.
Constraints
1 <= n <= 20-1000 <= matrix[i][j] <= 1000- Modify the matrix in place — do not allocate another 2D matrix.
Examples
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; rotate(matrix); // matrix is now: // [[7, 4, 1], // [8, 5, 2], // [9, 6, 3]]
const matrix = [ [1, 2], [3, 4] ]; rotate(matrix); // [[3, 1], // [4, 2]]
Solution
Reveal solution
function rotate(matrix) {
const n = matrix.length;
// Transpose
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]];
}
}
// Reverse each row
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
return matrix;
}Transpose the matrix (swap across the diagonal), then reverse each row. Both operations together yield a 90° clockwise rotation.
Resources
NameTopicDifficulty
103 of 103 problems