Limit Occurrences in Sorted Array Problem
Description
LeetCode Problem 3940.
You are given a sorted integer array nums and an integer k.
Return an array such that each distinct element appears at most k times, while preserving the relative order of the elements in nums.
Note: If a distinct element appears at least k times, then it must appear exactly k times in the resulting array.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,1,2,2,3]
Explanation:
Each element can appear at most 2 times.
- The element 1 appears 3 times, so only 2 occurrences are kept.
- The element 2 appears 2 times, so both occurrences are kept.
- The element 3 appears 1 time, so it is kept.
Thus, the resulting array is [1, 1, 2, 2, 3].
Example 2:
Input: nums = [1,2,3], k = 1
Output: [1,2,3]
Explanation:
All elements are distinct and already appear at most once, so the array remains unchanged.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100numsis sorted in non-decreasing order.1 <= k <= nums.length
Follow-up:
- Can you solve this in-place using O(1) extra space?
- Note that the space used for returning or resizing the result does not count toward the space complexity mentioned above, as some languages do not support in-place resizing.
Solution
Approach: Two Pointers
Because the array is sorted, equal values are next to each other. We scan once, counting how long the current run of equal values is. The first element is always kept, so the write position l starts at 1.
For each r from 1: if nums[r] differs from nums[r - 1] the run restarts at 1, otherwise it grows by one. If the run length is at most k, we copy nums[r] to nums[l] and move l forward. The answer is the first l elements.
This works in place, so the only extra space is the returned copy.
Complexity: O(n) time and O(1) extra space.
class Solution:
def limitOccurrences(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
cnt = l = 1
for r in range(1, n):
if nums[r] != nums[r - 1]:
cnt = 1
else:
cnt += 1
if cnt <= k:
nums[l] = nums[r]
l += 1
return nums[:l]