AlgoLounge

Limit Occurrences in Sorted Array

easy

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.

Examples

Example 1

Input:  nums = [1,1,1,2,2,3], k = 2
Output: [1,1,2,2,3]

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]

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.
TypeScript
Loading editor…
List of test cases (12)
Case 1
nums = [1,1,1,2,2,3]
k = 2
Case 2
nums = [1,2,3]
k = 1
Case 3
nums = [1,1,1,1]
k = 1
Case 4
nums = [1,1,1,1]
k = 4
Case 5
nums = [1,1,1,1]
k = 3
Case 6
nums = [5]
k = 1
Case 7
nums = [1,2,2,3,3,3,4,4,4,4]
k = 2
Case 8
nums = [7,7,7,8,8,9,10,10,10,10]
k = 3
Case 9
nums = [1,1,2,2,3,3,4,4,5,5]
k = 2
Case 10
nums = [100,100,100,100,100]
k = 2
Case 11
nums = [1,2,3,4,5,6,7,8,9,10]
k = 5
Case 12
nums = [1,1,1,2,3,4,5,5,5,6,6,7]
k = 2