Given a sorted array, remove extra duplicates so that each value appears at most a fixed number of times.
Remove Duplicates from Sorted Array II
gfgProblem
You are given a sorted integer array nums and an integer k.
Modify the array in place so that each distinct value appears at most k times, while preserving the relative order of the kept elements.
Return the length of the modified array. The first returned-length elements of nums should contain the valid result.
Goal
Keep as many elements as allowed by the k-occurrence limit, and discard extra occurrences of the same value.
Because the array is already sorted, equal values are adjacent.
Notes
- The operation must be done in-place.
- You only need to ensure the prefix of length
newLengthis correct. - Any values beyond the returned length do not matter.
Input Format
nums: a sorted integer arrayk: a non-negative integer limit
The exact input representation may vary by platform, but the core task is to process one sorted array with a per-value occurrence cap.
Output Format
Return the length of the array after removing extra occurrences. The array should be updated in place so that its first length positions contain the kept elements.
Constraints
numsis sorted in non-decreasing order- Keep at most
koccurrences of each distinct value - Preserve the relative order of kept elements
- Solve with O(1) extra space if possible
Example 1
Input
nums = [1,1,1,2,2,3], k = 2
Output
5
Explanation
After limiting each value to at most 2 occurrences, the array becomes [1,1,2,2,3]. The returned length is 5.
Example 2
Input
nums = [0,0,1,1,1,1,2,3,3], k = 2
Output
7
Explanation
The kept prefix can be [0,0,1,1,2,3,3]. Each value appears at most twice, so the new length is 7.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.