Rotate Image
MediumMath & Geometry · Apple · NVIDIA
You are given an n x n integer matrix. Rotate it 90 degrees clockwise and return it.
After rotation, the first column read from bottom to top becomes the first row, the second column read bottom to top becomes the second row, and so on.
Try to rotate the matrix in place with O(1) extra space (modify matrix directly and return it). Returning a newly built matrix is also accepted by the tests, but the interviewer will expect the in-place approach.
Example 1
- Input:
- matrix = [[1,-2],[3,4]]
- Output:
- [[3,1],[4,-2]]
- Explanation
- Rotating clockwise turns the left column (top to bottom 1, 3) into the top row read right to left, giving the top row [3,1]; the right column (-2, 4) becomes the bottom row [4,-2].
Example 2
- Input:
- matrix = [[2,4,6],[8,10,12],[14,16,18]]
- Output:
- [[14,8,2],[16,10,4],[18,12,6]]
- Explanation
- The first column read bottom to top (14, 8, 2) becomes the first row. The centre value 10 stays where it is.
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000