Rotate a list
Rotating a list right by one step moves every item one slot to the right, and the last item wraps around to the front. You get a list of integers nums and a count k (0 or more). Apply that one-step move to nums, k times over.
Change the list in place: rearrange the items inside the caller's list instead of handing back a new one. The tests read nums after your function returns and ignore anything it returns. k can be larger than the length of the list.
Once it works, aim for O(1) extra space: a few variables, no second list.
nums = [10, 20, 30, 40, 50], k = 2Outputnums becomes [40, 50, 10, 20, 30]The last two items, 40 and 50, wrap around to the front. The other three move two slots right.
nums = [1, 2, 3], k = 4Outputnums becomes [3, 1, 2]Three steps bring every item back to where it started, so only 4 % 3 = 1 step matters.
nums = [6, -2, 9, 4], k = 4Outputnums stays [6, -2, 9, 4]Rotating by the length of the list puts every item back in its own slot.
1 ≤ len(nums) ≤ 2 · 105
-109 ≤ nums[i] ≤ 109
0 ≤ k ≤ 109
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.