mediumMatrixArrays & Hashing

Rotate Image

mediumTime: O(n^2)Space: O(1)

Signals to notice

rotate matrix 90° clockwise in-placelayer-by-layer swaptranspose + reverse

Brute force first

Create new matrix, copy rotated positions. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Transpose the matrix (swap rows and columns), then reverse each row. Or rotate layer by layer with four-way swaps. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

90° clockwise rotation = transpose (swap matrix[i][j] with matrix[j][i]) followed by horizontal flip (reverse each row). These two operations compose to produce the rotation. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Transposing the full matrix instead of just the upper triangle — swapping (i,j) and (j,i) twice puts them back. Only swap when i < j. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern