~/problems / Two pointers

Rotate Array

medium ~20 min

A circular LED banner stores its pixels in a list. Scrolling it by k steps moves every value k places to the right, and values that fall off the end wrap around to the front.

Write shift_right(nums: list[int], k: int) -> None that performs this shift in place. Return nothing; the caller looks at nums.

  • After the call, the value that was at index i sits at index (i + k) % len(nums).
  • k can be larger than the length of the list.
nums = [1, 2, 3, 4, 5, 6, 7]
shift_right(nums, 3)
nums   # [5, 6, 7, 1, 2, 3, 4]

nums = [10, 20]
shift_right(nums, 5)
nums   # [20, 10]

nums = [4]
shift_right(nums, 0)
nums   # [4]

Constraints: 1 <= len(nums) <= 2 * 10^5; 0 <= k <= 10^9; values are in [-10^9, 10^9].

Moving the list one step at a time k times is O(n·k), too slow here. Aim for O(n) time and O(1) extra space: no slices, no second list.

Show hint

try reversing the whole list and look at where the two blocks you need ended up. What would fix each block?

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc