Funcia
Lv.1arraytwo-pointers

Keep at Most K Copies

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

nums is sorted in non-decreasing order. Keep at most the first k copies of every value, delete the rest, and return the remaining array (still sorted).

Examples

numskresult
[1, 1, 1, 2, 2, 3]2[1, 1, 2, 2, 3]
[0, 0, 1, 1, 1, 1, 2, 3, 3]1[0, 1, 2, 3]
[5, 5, 5]4[5, 5, 5]

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[], k: int) → int[]

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000
  • −109≤-10^9 \le nums[i] ≤109\le 10^9, sorted in non-decreasing order
  • 1≤1 \le k ≤200,000\le 200{,}000

Expected complexity

Time
O(N)
Space
O(1) extra

Examples

numskExpected
[1,1,1,2,2,3]2[1,1,2,2,3]
[0,0,1,1,1,1,2,3,3]1[0,1,2,3]
[5,5,5]4[5,5,5]

Hint

Hint

Equal values are adjacent. Write kept elements with a pointer w; keep nums[i] when w < k or nums[w - k] != nums[i]. Erasing from the middle of the array for every deletion is O(N2)O(N^2) and exceeds the time limit; one pass is O(N)O(N).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251112 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.