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
gfgYou 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.
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.
newLength is correct.nums: a sorted integer arrayk: a non-negative integer limitThe exact input representation may vary by platform, but the core task is to process one sorted array with a per-value occurrence cap.
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.
nums is sorted in non-decreasing orderk occurrences of each distinct valueExample 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
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.