Python coding

Keep at most k copies, in place

nums is sorted in non-decreasing order and may be empty, and k ≥ 1. Rewrite it in place so each value appears at most k times, keeping the original order, and return the kept part: the first length elements of nums, where length is how many you kept.

Use O(1) extra space: overwrite nums as you read it instead of building a second list.

  • keep_k_copies([4,4,4,6,6,9], 2) → [4,4,6,6,9]
  • keep_k_copies([1,1,2,3,3,3,3], 1) → [1,2,3]
  • keep_k_copies([0,0,0,0], 3) → [0,0,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Read every value once and keep a write index: a value you keep goes to nums[write], then write += 1.

Hint 2

The list is sorted, so x already has k kept copies exactly when nums[write - k] == x. The first k values are always kept.

Solution and why it works
pythonO(n) · O(1) extra, the returned slice aside
def keep_k_copies(nums: list[int], k: int) -> list[int]:
    write = 0
    for x in nums:                           # reads stay ahead of write
        if write < k or nums[write - k] != x:
            nums[write] = x
            write += 1
    return nums[:write]

write marks the next kept slot and never gets ahead of the read position, so overwriting is safe. Because the list is sorted, the kept part already ends with k copies of x exactly when nums[write - k] == x. Compare against the kept part, not the read position minus k: that slot may already be overwritten, and [4, 4, 4, 6, 6, 9] with k = 2 would lose a 6. One pass, O(1) extra space.

Related lab: Loops in motion