Rotate Array
MediumTop Interview 150 Arrays & HashingAppleFiverrBoxProblem
You are given an integer array nums and a non-negative integer k. Move the array's
contents k places to the right: every item shifts right by k positions, and items that
fall off the end wrap around to the front.
Change nums in place. The method returns nothing; the answer is the array after the call.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- 0 ≤ k ≤ 10⁹ (k may be larger than the array length)
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: Every item is swapped at most once in each of the three reversal passes.
Space: Only a few index variables and one temporary value are used; the array is changed in place.
Reduce k with k mod n. Reverse the whole array, then reverse the first k items, then reverse
the remaining n − k items. The last k items land at the front in their original order, and the others follow.