Rotate Image
MediumNeetCode 150Top Interview 150 Math & GeometrySIGRakutenCitigroupQualcommProblem
You get a square grid of numbers with n rows and n columns.
Turn the grid 90 degrees clockwise. You must change the grid in place: do not build a second grid. Nothing is returned.
Constraints
- n = matrix.length = matrix[i].length
- 1 ≤ n ≤ 20
- -1000 ≤ matrix[i][j] ≤ 1000
Examples: pick one to animate
Solutions
TimeO(n²)
SpaceO(1)
Time: Each of the n² cells is moved a constant number of times: once by the transpose and once by the row flip.
Space: Cells are swapped in place, so only a few index variables are stored.
A clockwise turn is two simple moves. Transpose the grid (swap each cell with its mirror across the
main diagonal), then reverse every row. Together they send the cell at row i, column j
to row j, column n-1-i, which is exactly a quarter turn.