Why it works
- After the shift the last k numbers stand at the front, and the rest follow them. Reversing the whole array already puts each group in its place, only each group is backwards.
- Reversing each group on its own turns it the right way round again, so the order inside each group is the old one.
- A shift by n brings the array back to where it was, so a k of n or more shifts the same as k mod n. Take k = k mod n first, or the reverse of the first k runs past the end.
Complexity
Time O(n): the three reverses swap each number at most twice. Memory O(1): the numbers trade places inside the same array, with no second one.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗