Skip to main content
Back to problems
Leetcode
Medium
Arrays
Ordered Structures
Binary Search
Limit Occurrences In Sorted Array

Given a sorted array, remove extra duplicates so that each value appears at most a fixed number of times.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Remove Duplicates from Sorted Array II

gfg
Primary
Problem Statement

Problem

You 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.

Goal

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.

Notes

  • The operation must be done in-place.
  • You only need to ensure the prefix of length newLength is correct.
  • Any values beyond the returned length do not matter.

Input Format

  • nums: a sorted integer array
  • k: a non-negative integer limit

The exact input representation may vary by platform, but the core task is to process one sorted array with a per-value occurrence cap.

Output Format

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.

Constraints

  • nums is sorted in non-decreasing order
  • Keep at most k occurrences of each distinct value
  • Preserve the relative order of kept elements
  • Solve with O(1) extra space if possible
Examples
Sample cases returned by the problem API.

Example 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

Unlock deeper context for this problem

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.