Keep at Most K Occurrences in a Sorted Array
Updated
Problem statement
You are given an integer array nums sorted in nondecreasing order and a nonnegative integer k. Compact nums in place so that every distinct value appears at most k times while preserving sorted order.
Return an array containing exactly the compacted prefix. The compaction must use O(1) auxiliary space; the returned array used to expose that prefix to the judge is not counted as auxiliary workspace. If k is 0, return an empty array.
Function
keepAtMostK(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,1,2,2,3]The third 1 is removed; every other occurrence fits within the limit of two.
Example 2
nums = [0,0,0,1,1,1]k = 1return = [0,1]Only the first occurrence of each distinct value remains.
Example 3
nums = [-2,-2,3]k = 0return = []A zero occurrence limit removes every value.
Constraints
0 <= nums.length <= 100000-1000000000 <= nums[i] <= 10000000000 <= k <= nums.lengthwhennumsis non-empty.k = 0whennumsis empty.numsis sorted in nondecreasing order.
More Oracle Onsite Interview questions
- Course ScheduleONSITE INTERVIEW · Seen Nov 2026
- Shortest Subarray with Sum at Least KONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Minimum Meeting RoomsONSITE INTERVIEW · Seen Nov 2026
- Shortest Window with Required CountsONSITE INTERVIEW · Seen Nov 2026
- Maximum Subarray Sum with One DeletionONSITE INTERVIEW · Seen Nov 2026
- Shortest Deletion for Distinct CharactersONSITE INTERVIEW · Seen Nov 2026
- Count Dropped Rate-Limited RequestsONSITE INTERVIEW · Seen Nov 2026
- Design Authentication ManagerONSITE INTERVIEW · Seen Oct 2026
- Maximum Bouquet ValueONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Valid Triangle NumberBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Count Winning Dice Face PairsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Merge Sorted Squares of Two ArraysWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Run-Length Encoded Vector Dot ProductMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Sort Ones, Twos, and Threes In PlaceAgoda · PHONE SCREEN · ONSITE INTERVIEWAgoda interview questions
- Minimum Station Tracks for a Train ScheduleBNSF Railway · ONSITE INTERVIEWBNSF Railway interview questions
- Candy Crush Grid Matching and GravityRoblox · PHONE SCREEN · ONSITE INTERVIEWRoblox interview questions
- Longest Binary Window with at Most K OnesLinkedIn · ONSITE INTERVIEWLinkedIn interview questions