Rotate an array by k
Reverse the whole array, then reverse the first k, then reverse the rest. Three passes, every element moved exactly twice, O(1) extra space. The slice version a[-k:] + a[:-k] is one line and allocates a second array.
Overview
Why three reversals work
A right rotation by k moves the last k elements to the front and slides the rest along. Reversing the whole array puts those k at the front immediately — but reversed, and the other block reversed too. Reversing each block separately undoes exactly that.
Total work is 3·n/2 swaps, so O(n) time, and the only storage is a couple of indices.
Step through it
What to watch
- After the first reversal the blocks are in the right places, backwards.
- Each subsequent reversal fixes one block.
- Nothing is allocated — every step is in-place swapping.
Say this out loud
"Three reversals: whole thing, first k, then the rest. O(n) time, O(1) space. And k needs to be k % n first, or a k larger than the array breaks it."