Intuition
A 90° clockwise rotation equals two simple in-place moves: transpose the matrix (swap across the main diagonal), then reverse each row. Together they send every element to its rotated position.
Approach
Copying into a new matrix is the easy way out
You can allocate a fresh n×n grid and place each element at its rotated coordinate using a formula. That's straightforward but uses O(n²) extra space, which the in-place requirement forbids. The insight is that a rotation can be decomposed into two simpler in-place operations that compose to the same result.
A 90° rotation = transpose + reverse rows
Transposing the matrix swaps matrix[i][j] with matrix[j][i], turning rows into columns — this gets every element onto the correct line but mirrored. Reversing each row afterward flips that mirror, landing every element in its final rotated position. It's worth convincing yourself on a small example: together these two flips equal a clockwise quarter-turn.
Transpose carefully, then reverse
Do the transpose with the inner loop starting at j = i + 1, so each off-diagonal pair is swapped exactly once — swapping the full grid would undo itself. Then reverse each row in place. Both steps touch each cell a constant number of times: O(n²) time, O(1) extra space. A 1×1 grid is a no-op, as a rotation should be.
Solution & live demo
Edge cases
Transpose and row-reverse are both no-ops; the single cell is unchanged, as a rotation should leave it.
One diagonal swap plus two row reversals produce the correct 90° turn.
Restricting the transpose to j > i ensures each off-diagonal pair is swapped exactly once.