Rotate matrix by 90 degrees
MediumTranspose, then reverse each row
Problem
Given an N * N 2D integer matrix, rotate the matrix by 90 degrees clockwise. The rotation must be done in place, meaning the input 2D matrix must be modified directly.
Transpose the grid (swap rows/columns), then reverse each row — that's a 90° turn.
The idea
Transposing swaps rows with columns, and reversing each row afterwards completes the clockwise quarter turn. Both steps are in place, so the whole rotation needs no second matrix.
The trick
- Transpose only the upper triangle (j > i) or you undo your own swaps.
- Anticlockwise is transpose then reverse each column instead.
- O(n²) time, O(1) space.
Step 1 of 8. Rotate 90° clockwise = transpose (swap across the diagonal), then reverse each row.
Two in-place passes.
1for (let i=0;i<n;i++) for (let j=i+1;j<n;j++)2 [M[i][j], M[j][i]] = [M[j][i], M[i][j]]; // transpose3for (const row of M) row.reverse(); // mirrorInput
- grid
- 3 × 3
Memory
- cells marked
- 0
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
- Explanation:
- Each column becomes a row.
Example 2
- Input:
- matrix = [[1,2],[3,4]]
- Output:
- [[3, 1], [4, 2]]
- Explanation:
- Turns 90° clockwise to [[3,1],[4,2]].
Example 3
- Input:
- matrix = [[1]]
- Output:
- [[1]]
- Explanation:
- One cell stays put.
Constraints
- n == matrix.length.
- n == matrix[i].length.
- 1 <= n <= 100.
- -10^4 <= matrix[i][j] <= 10^4
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.