Problem Statement
Given a sorted integer array, remove duplicates in-place such that each unique element appears at most K times. Return the new length of the modified array.
You must do this with:
- O(n) time complexity
- O(1) extra space (modify the array in-place)
The relative order of elements should be maintained. Elements beyond the returned length don't matter.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4numsis sorted in non-decreasing order1 <= K <= nums.length
Example
Input: nums = [1, 1, 1, 2, 2, 2, 3, 3], K = 2
Output: 6, array becomes [1, 1, 2, 2, 3, 3, ...]
Explanation: Each element appears at most 2 times.
Input: nums = [0, 0, 0, 0, 1, 1, 1, 1, 2], K = 3
Output: 7, array becomes [0, 0, 0, 1, 1, 1, 2, ...]
Follow-ups
- What if K = 1? Can you simplify the logic?
- What if the array is NOT sorted? Does your approach still work?
- Can you generalize this to work with any arbitrary predicate (not just duplicate count)?
- What's the key insight that makes the two-pointer approach work here?