mediumMath / GeometryPure DSA~22 min
Rotate Shift Roster In Place
A weekly shift roster is stored as a square grid. When the team rotates the on-call display by a quarter turn, you must rotate the matrix 90° clockwise without allocating a second grid.
Problem
Given an n × n matrix, rotate it 90 degrees clockwise in place. You must modify the input matrix directly and use O(1) extra space.
Input
An n × n integer matrix (1 ≤ n ≤ 20), values fit in 32-bit ints.
Output
The same matrix rotated 90° clockwise (mutated in place).
Constraints
- n == matrix.length == matrix[i].length
- 1 ≤ n ≤ 20
- Extra space must be O(1) — no second matrix
Examples
Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]
Top row 1,2,3 becomes the right column.
Example 2
Input
[[1,2],[3,4]]
Output
[[3,1],[4,2]]
A 2×2 quarter turn clockwise.