Rotate Array
Shift every value k places round. Reverse the whole thing, then each part, and it is done in place.
Result · step 11 of 11Rotate, Partition, Select: Rotate right by 3
Rotated by 3 in 6 swaps. Every value moved at most twice, so O(n) time and O(1) extra space.
What you will see
Reverse whole -> reverse first k -> reverse rest; each reversal shows crossing pairs.
Cost
| Best | O(n) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Space | O(1) |
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.
Screen readers: Each cell is announced as index, value and state; each step's accessibility text states the decision and its effect.
Reduced motion: Swaps and shifts become value crossfades with an outline flash; pointers appear at their destination.
Before this
Variants
- Reversal Method Three in-place reversals.
- Juggling / Cycle Method Follow gcd(n, k) cycles.
Taught by the same lesson
Rotate, Partition, Select covers these too, in the same run.