Rotate Image
Medium· in-place· transpose
Problem
Rotate an n × n matrix 90 degrees clockwise. The rotation must be done in place, without allocating 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]]
Constraints
- • n == matrix.length == matrix[i].length
- • 1 <= n <= 20
Hints & approach
Hint 1
Track where element (i, j) ends up after a clockwise rotation.
Hint 2
A rotation can be decomposed into two simpler reflections.
Hint 3
Transpose the matrix, then reverse each row.
Approachtry the hints first
A clockwise rotation sends (i, j) to (j, n-1-i). That equals a transpose, which swaps (i, j) with (j, i), followed by reversing every row. Both steps are simple in-place swaps. Alternatively, rotate four cells at a time layer by layer.
Time O(n²) · Space O(1)