Skip to main content

Limit Occurrences in Sorted Array - Solution & Explanation

EasyArrayTwo Pointers9 min read
Practice this problem

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 <= 100
  • 1 <= nums[i] <= 100
  • nums is 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:

  1. If nums[r] \ne nums[r - 1], we meet a new value, so reset cnt to 1.
  2. If nums[r] = nums[r - 1], it is a duplicate, so increment cnt by 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

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force ShiftingO(n^2)O(1)Conceptual understanding or very small arrays
Counting with Overwrite PointerO(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 is generally considered an Easy problem. The challenge is recognizing that sorted order allows duplicate checks using simple index comparisons. Once the two-pointer pattern is applied, the implementation becomes straightforward.
Limit Occurrences in Sorted Array Python/Java solution
Python and Java implementations both follow the same pattern: maintain a write pointer and iterate through the array with a read pointer. When the element does not violate the allowed occurrence limit, assign it to the write index and increment the pointer. This produces an in-place O(n) solution with constant extra memory.
How to solve Limit Occurrences in Sorted Array in O(n)?
Use a two-pointer approach. Maintain a write index and iterate through the array with a read pointer. For each element, check whether placing it would exceed the allowed number of duplicates by comparing it with the element k positions behind the write index. If valid, copy it and move the write pointer forward.
What is the best approach for Limit Occurrences in Sorted Array?
The best approach uses a two-pointer technique. A slow pointer tracks where the next valid element should be written while a fast pointer scans the array. Because the array is sorted, comparing the current value with the element k positions before the write pointer ensures no value appears more than k times. This solution runs in O(n) time with O(1) extra space.
Is Limit Occurrences in Sorted Array asked at Google/Amazon/Meta?
Duplicate removal and frequency-limiting problems on sorted arrays frequently appear in interviews at companies like Google, Amazon, and Meta. Variants such as "Remove Duplicates from Sorted Array" and "Remove Duplicates from Sorted Array II" test the same two-pointer pattern and in-place array manipulation.
What data structure is used in Limit Occurrences in Sorted Array?
The problem mainly uses arrays with the two-pointer technique. Since the input array is already sorted, duplicates can be detected using index comparisons instead of hash maps or extra storage.
What is the time complexity of Limit Occurrences in Sorted Array?
The optimal algorithm runs in O(n) time because the array is scanned once using two pointers. Each element is read once and written at most once. Space complexity is O(1) since the modification happens directly inside the input array.

Ready to solve this problem?

Practice Limit Occurrences in Sorted Array with our built-in code editor and test cases.

Practice on FleetCode