Rotate a 2D square matrix by 90 degrees clockwise in place.
Problem Statement
Examples
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Explanation: The matrix is rotated 90 degrees clockwise in-place.
Input: matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
Output: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
Explanation: The matrix is rotated 90 degrees clockwise in-place.
Complexity
Time Complexity: O(N²)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
A 90-degree clockwise rotation transforms element (i, j) to (j, n - 1 - i). This transformation is equivalent to matrix transposition followed by horizontal reflection (reversing each row).
Step-by-Step Approach
- Transpose the matrix: iterate
ifrom0ton - 1, andjfromi + 1ton - 1, swappingmatrix[i][j]andmatrix[j][i]. - Reverse each row: for each row
i, callmatrix[i].reverse(). - Return
matrix.
Optimal Implementation (JavaScript)
function rotateMatrix(matrix) {
const n = matrix.length;
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]];
}
}
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
return matrix;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- 1x1 matrix: unchanged.
- 2x2 matrix: immediate 4-way swap.