You are given matrix, an n × n grid of integers.
Rotate it 90 degrees clockwise in place: change matrix itself rather than building and
returning a new grid. After the turn, the first row holds what was the first column, read from
bottom to top.
Example 1
- Input
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Output
- [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Example 2
- Input
- matrix = [[1, 2], [3, 4]]
- Output
- [[3, 1], [4, 2]]
Constraints
- 1 ≤ n ≤ 20
- Every value is between −1000 and 1000.
Show the pattern
Math and matrices
A quarter turn is index arithmetic: cell (r, c) moves to (c, n − 1 − r). Doing it in place means moving cells in cycles of four, or as two simpler flips.
Show the approach
A clockwise quarter turn sends cell (r, c) to (c, n − 1 − r). That is two easy in-place steps:
transpose the grid (swap matrix[r][c] with matrix[c][r] for every c > r), which sends (r, c)
to (c, r), then reverse each row, which sends (c, r) to (c, n − 1 − r).
Time: O(n²) · Space: O(1)