Rotate an n by n matrix by 90 degrees clockwise. Do it in place, without a second matrix.
DSA Animator › DSA Revision › Matrix › Rotate Image
Remember: clockwise rotation equals transpose, then reverse each row. Counter-clockwise is transpose, then reverse each column. The video solves Rotate Image (LeetCode 48, Medium) with the Transpose + Reverse pattern from the Matrix topic, and you can replay every step in the interactive Rotate Image animation.
Rotate an n by n matrix by 90 degrees clockwise. Do it in place, without a second matrix.
1 2 3, 4 5 6, 7 8 9 becomes 7 4 1, 8 5 2, 9 6 3.
Copying into a new matrix, where row i becomes column n minus 1 minus i, is easy but uses O of n squared space. Two simple in-place steps do the same thing.
First transpose: swap every cell across the main diagonal, so rows become columns. Then reverse each row. Together, those two steps are a 90 degree clockwise rotation.
Transposing swaps 2 with 4, 3 with 7, and 6 with 8. The matrix is now 1 4 7, 2 5 8, 3 6 9. Reverse each row: 7 4 1, 8 5 2, 9 6 3. That is the rotated image.
In code, loop over the upper triangle and swap each cell with its mirror across the diagonal. Then reverse every row with two pointers. Each cell moves a constant number of times, so it's O of n squared time and O of 1 space.
Remember: clockwise rotation equals transpose, then reverse each row. Counter-clockwise is transpose, then reverse each column.