Rotate an n×n matrix 90° clockwise in place, using no second matrix. e.g. [[1,2,3],[4,5,6],[7,8,9]] → [[7,4,1],[8,5,2],[9,6,3]].
Decomposing an in-place rotation into two simple reversible passes — transpose then reverse each row — instead of juggling four-way index swaps.
The clean in-place trick is to factor the rotation into two operations you already trust. Transpose the matrix (swap a[i][j] with a[j][i], iterating only j > i so you don't undo it), which reflects across the main diagonal; then reverse each row. Transpose + row-reverse = 90° clockwise; transpose + column-reverse (or reverse rows first) gives counter-clockwise. Both passes use O(1) extra space and touch each cell once, so O(n^2) time. The alternative — rotating four cells at a time in concentric rings — is also O(1) space but far more error-prone to write under pressure. Recognition signal: 'rotate/reflect a square matrix in place' → express the geometric transform as a composition of transpose and axis reversals.
In-place square-matrix rotation or reflection → compose transpose with row/column reversal rather than hand-rolling four-way ring swaps.
Time O(n²) · Space O(1)