k ≥ n
When k equals or exceeds n, the modulo operation reduces it. A full rotation of n steps returns the array to its original position.
A circular conveyor belt of packages needs its last k items moved to the front. Shifting one item at a time costs O(n·k) moves. The elegant alternative: reverse the entire belt, then reverse the first k items, then reverse the remaining n − k. Three in-place reversals achieve a full rotation. O(n) time. O(1) space.
Step 1: Reverse the entire array — this puts
the tail block (which should move to front) into position, but
both blocks are backwards.
Step 2: Reverse the first k elements — fixes
the front block.
Step 3: Reverse the remaining n−k elements —
fixes the back block.
Three reversals compose a rotation. Each reversal is an in-place two-pointer sweep — no extra array is needed.
Compute k = k % n. If k is zero or a multiple of n, the array is unchanged.
Reverse all n elements. The last k elements are now at the front — but in the wrong order.
Reverse elements 0 through k − 1. They are now in the correct rotated order.
Reverse elements k through n − 1. The full rotation is complete.
Understanding boundary behavior is as important as the main algorithm path.
When k equals or exceeds n, the modulo operation reduces it. A full rotation of n steps returns the array to its original position.
No rotation is needed. All three reversals cancel out — the array is untouched.
Time: O(n) — each element touched at most twice.
Space: O(1) — in-place swaps.