[LeetCode] Limit Occurrences in Sorted Array

3940. Limit Occurrences in Sorted Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> limitOccurrences(vector<int>& nums, int k) {
vector<int> res;
for(int i = 0, x = -1, cnt = 0; i < nums.size(); i++) {
if(x == nums[i]) cnt++;
else x = nums[i], cnt = 1;
if(cnt <= k) res.push_back(x);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/limit-occurrences-in-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.