Rotate Image
Medium · Matrix · Array · Matrix · Math
Problem
Rotate an n x n matrix by 90 degrees clockwise, in place. Do not allocate a second matrix.
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
The first column becomes the first row, reversed.
Input: matrix = [[1,2],[3,4]] Output: [[3,1],[4,2]]
Constraints
- n == len(matrix) == len(matrix[i])
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
- The rotation must happen in place
Approaches
- Two mirrors, anti-diagonal then horizontal — time O(n²), space O(1)
Related problems
Start free on Cariara · Coding problems · System design studio