iq.lab
Python starts when a code cell comes near or you run one
mediumLoops and basicsTwo pointers target 25 min

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.

Example 1
Inputnums = [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.

Example 2
Inputnums = [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.

Example 3
Inputnums = [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.

Constraints
  • 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.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.