Limit Occurrences in Sorted Array - Solution & Explanation
Problem Statement
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.
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.
Approach Overview
Problem Overview: You are given a sorted array and must ensure each distinct value appears no more than k times. Extra duplicates should be removed in-place while preserving the original order. The task typically returns the new valid length of the array after limiting occurrences.
Approach 1: Brute Force Shifting (O(n^2) time, O(1) space)
The simplest idea is to scan the array and count how many times the current number appears consecutively. When the count exceeds the allowed limit k, shift all remaining elements one position left to overwrite the extra occurrence. This approach works because the array is already sorted, so duplicates appear next to each other. However, repeated shifting creates a quadratic worst-case cost when many elements must be moved multiple times. This method demonstrates the core constraint but is rarely acceptable in interviews for large inputs.
Approach 2: Counting with Overwrite Pointer (O(n) time, O(1) space)
Instead of shifting elements repeatedly, maintain a write index that marks where the next valid value should go. Iterate through the array while counting occurrences of the current number. If the count is less than or equal to k, copy the element to the write position and advance it. If the count exceeds k, simply skip the element. Because each element is processed once and written at most once, the algorithm runs in linear time. This method uses basic arrays manipulation and avoids unnecessary data movement.
Approach 3: Two Pointers with Window Check (O(n) time, O(1) space)
The cleanest solution uses the two pointers technique. Maintain a slow pointer that tracks the position for the next valid element and iterate a fast pointer through the array. For each value, check whether placing it would violate the allowed occurrence limit. This can be done by comparing the current value with the element k positions before the slow pointer. If they differ, the value is valid and written at the slow index; otherwise it is skipped. Because the array is sorted, this comparison guarantees that no element appears more than k times in the result.
This two-pointer strategy performs a single linear pass and modifies the array in place. No auxiliary data structures are needed, which keeps the space complexity constant. The pattern appears frequently in sorted-array problems involving duplicate removal or compaction.
Recommended for interviews: The two-pointer approach is the expected solution. Interviewers want to see that you recognize how sorted order enables constant-time duplicate checks without additional memory. Mentioning the brute-force shifting method shows baseline reasoning, but implementing the linear-time two-pointer technique demonstrates familiarity with common array patterns and in-place optimization.
Solution
We define two pointers, l and r, where l is the write position and r is the current read position. We also use a counter cnt to record how many times the current value has appeared. Initially, both l and cnt are set to 1.
Then we traverse the array starting from r = 1:
- If
nums[r] \ne nums[r - 1], we meet a new value, so resetcntto 1. - If
nums[r] = nums[r - 1], it is a duplicate, so incrementcntby 1.
If cnt \le k, the occurrence limit is not exceeded, so we keep this element by writing nums[r] to nums[l], then move l one step to the right.
Finally, return the first l elements, i.e., nums[:l].
The time complexity is O(n), where n is the length of the array. The space complexity is O(1), since only constant extra space is used.
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Shifting | O(n^2) | O(1) | Conceptual understanding or very small arrays |
| Counting with Overwrite Pointer | O(n) | O(1) | When you want a clear linear scan with explicit duplicate counting |
| Two Pointers (Optimal) | O(n) | O(1) | Sorted arrays where duplicates must be limited in-place |
Video Solution
Limit Occurrences in Sorted Array | LeetCode 3940 | Weekly Contest 503 | Java | Developer Coder • Developer Coder • 143 views views
Watch 8 more video solutions →Frequently Asked Questions
Is Limit Occurrences in Sorted Array easy or hard?
Limit Occurrences in Sorted Array Python/Java solution
How to solve Limit Occurrences in Sorted Array in O(n)?
What is the best approach for Limit Occurrences in Sorted Array?
Is Limit Occurrences in Sorted Array asked at Google/Amazon/Meta?
What data structure is used in Limit Occurrences in Sorted Array?
What is the time complexity of Limit Occurrences in Sorted Array?
Ready to solve this problem?
Practice Limit Occurrences in Sorted Array with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor