mediumMath / GeometryPure DSA~20 min
Rotate An Image Grid 90° In Place
An image editor stores a square bitmap as an n x n matrix of pixels. Rotate it 90° clockwise without allocating a second matrix.
Problem
Given an n x n matrix representing an image, rotate it 90 degrees clockwise in place. You must modify the input matrix directly and use O(1) extra space.
Input
An n x n integer matrix.
Output
The same matrix, rotated 90° clockwise (modified in place).
Constraints
- 1 ≤ n ≤ 20
- -1000 ≤ matrix[i][j] ≤ 1000
Examples
Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]
Each column (top→bottom) becomes a row (left→right).
Example 2
Input
[[1,2],[3,4]]
Output
[[3,1],[4,2]]
2x2 clockwise rotation.