236. Quarter Turn
A photo editor stores a square picture as an n × n grid of pixel values. It needs a quarter turn: rotate the picture 90 degrees clockwise, so that the first row becomes the last column, the second row becomes the second-to-last column, and so on. In other words, the pixel at row i, column j moves to row j, column n - 1 - i.
The device has very little memory, so you must do the rotation in place: change grid itself and do not allocate another grid of the same size. Nothing is returned. If the grid is not square, only its top-left k × k block, with k = min(rows, columns), is rotated and every other cell is left untouched.
Example 1
- Input:
- grid = [[1,2],[3,4]]
- Output:
- [[3,1],[4,2]]
- Explanation:
The first row [1,2] becomes the last column, and the second row [3,4] becomes the first column, giving [[3,1],[4,2]].
Example 2
- Input:
- grid = [[10,20,30],[40,50,60],[70,80,90]]
- Output:
- [[70,40,10],[80,50,20],[90,60,30]]
- Explanation:
Rows become columns from right to left: the first row [10,20,30] ends up as the last column, giving [[70,40,10],[80,50,20],[90,60,30]].
Example 3
- Input:
- grid = [[5]]
- Output:
- [[5]]
- Explanation:
A single pixel does not move.
Constraints
1 ≤ n ≤ 1000 for a square grid
-109 ≤ grid[i][j] ≤ 109
The function modifies grid and returns nothing.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Graded
- Your answer is read from
gridafter your method returns. - Time per case
- Python 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 ms
Expected complexity
- Time
- O(n<sup>2</sup>)
- Space
- O(1)