Given a list nums sorted in non-decreasing order and an integer k >= 1, rewrite nums in place so that every value appears at most k times, keeping the relative order. Return the new length n; only the first n slots of nums matter afterwards.
Tests read the list back with the walrus pattern (n := keep_at_most(a := [...], k), a[:n]), i.e. they check both the returned length and the prefix.
Examples
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: 5, and nums starts with [1, 1, 2, 2, 3]
Input: nums = [4, 4, 4, 4], k = 1
Output: 1, and nums starts with [4]
Constraints
0 <= len(nums) <= 10**5,1 <= k <= 10**5- Target: O(n) time, O(1) extra space (no new list).
Goals
- Use a slow write pointer and a fast read pointer
- Decide whether to keep an element by looking back k slots in the written prefix