Least Number of Unique Integers after K Removals
Least Number of Unique Integers after K Removals is a medium heaps problem solved with the top k / kth largest / smallest pattern.
The best approach, optimal (bucket by frequency), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from min-heap of frequencies up.
Problem
You are given an integer array arr and an integer k. You must delete exactly k elements from the array, choosing which ones freely. Return the smallest possible number of distinct values that can remain after the deletions.
Examples
Example 1
- Input
arr = [4, 4, 7, 1, 1, 1, 9], k = 2- Output
2- Why
- 7 and 9 each appear once. Removing both uses up k = 2 and leaves only 4 and 1.
Example 2
- Input
arr = [3, 3, 3, 8, 8, 5, 5, 5, 5], k = 4- Output
2- Why
- Removing both 8s costs 2. The remaining 2 removals cannot wipe out 3 (three copies) or 5 (four copies), so 3 and 5 stay.
Constraints
1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.length
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Min-heap of frequencies | O(n + d log d) | O(d) |
| Optimal (bucket by frequency) | O(n) | O(n) |
1Min-heap of frequencies
O(n + d log d)Counting is linear; each of the d distinct values is pushed and popped at most once.O(d)The map and heap hold one entry per distinct value.Count each value, push all frequencies into a min-heap, then keep popping the smallest frequency while the budget k can pay for it. Every pop erases one distinct value.
- Count occurrences with a hash map.
- Push every count into a min-heap.
- While the heap is not empty and its top is <= k: k -= top, pop.
- Return the heap size.
class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : arr) count.merge(x, 1, Integer::sum);
PriorityQueue<Integer> heap = new PriorityQueue<>(count.values());
while (!heap.isEmpty() && heap.peek() <= k) k -= heap.poll();
return heap.size();
}
}class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
count = {}
for x in arr:
count[x] = count.get(x, 0) + 1
heap = list(count.values())
heapq.heapify(heap)
while heap and heap[0] <= k:
k -= heapq.heappop(heap)
return len(heap)class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int, int> count;
for (int x : arr) count[x]++;
priority_queue<int, vector<int>, greater<int>> heap;
for (auto& p : count) heap.push(p.second);
while (!heap.empty() && heap.top() <= k) {
k -= heap.top();
heap.pop();
}
return (int)heap.size();
}
};function findLeastNumOfUniqueInts(arr, k) {
const count = new Map();
for (const x of arr) count.set(x, (count.get(x) || 0) + 1);
const heap = [];
const push = (v) => {
heap.push(v);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p] <= heap[i]) break;
[heap[p], heap[i]] = [heap[i], heap[p]];
i = p;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let s = i;
if (l < heap.length && heap[l] < heap[s]) s = l;
if (r < heap.length && heap[r] < heap[s]) s = r;
if (s === i) break;
[heap[s], heap[i]] = [heap[i], heap[s]];
i = s;
}
}
return top;
};
for (const c of count.values()) push(c);
while (heap.length > 0 && heap[0] <= k) k -= pop();
return heap.length;
}2Optimal (bucket by frequency)
O(n)Counting, filling the buckets and the walk over frequencies 1..n are each linear.O(n)The count map and the bucket array.A frequency is at most n, so instead of sorting the frequencies, count how many values have each frequency. Walk frequencies from 1 upward and erase as many values of that frequency as the budget allows.
- Count occurrences; let remaining = number of distinct values.
- buckets[f] = how many values occur exactly f times.
- For f = 1..n: take = min(buckets[f], k / f); remaining -= take; k -= take * f.
- If take < buckets[f], the budget cannot erase another value of this or any larger frequency, so stop.
- Return remaining.
class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
int n = arr.length;
Map<Integer, Integer> count = new HashMap<>();
for (int x : arr) count.merge(x, 1, Integer::sum);
int[] buckets = new int[n + 1];
for (int c : count.values()) buckets[c]++;
int remaining = count.size();
for (int f = 1; f <= n; f++) {
if (buckets[f] == 0) continue;
int take = Math.min(buckets[f], k / f);
remaining -= take;
k -= take * f;
if (take < buckets[f]) break;
}
return remaining;
}
}class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
n = len(arr)
count = {}
for x in arr:
count[x] = count.get(x, 0) + 1
buckets = [0] * (n + 1)
for c in count.values():
buckets[c] += 1
remaining = len(count)
for f in range(1, n + 1):
if buckets[f] == 0:
continue
take = min(buckets[f], k // f)
remaining -= take
k -= take * f
if take < buckets[f]:
break
return remainingclass Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
int n = arr.size();
unordered_map<int, int> count;
for (int x : arr) count[x]++;
vector<int> buckets(n + 1, 0);
for (auto& p : count) buckets[p.second]++;
int remaining = count.size();
for (int f = 1; f <= n; f++) {
if (buckets[f] == 0) continue;
int take = min(buckets[f], k / f);
remaining -= take;
k -= take * f;
if (take < buckets[f]) break;
}
return remaining;
}
};function findLeastNumOfUniqueInts(arr, k) {
const n = arr.length;
const count = new Map();
for (const x of arr) count.set(x, (count.get(x) || 0) + 1);
const buckets = new Array(n + 1).fill(0);
for (const c of count.values()) buckets[c]++;
let remaining = count.size;
for (let f = 1; f <= n; f++) {
if (buckets[f] === 0) continue;
const take = Math.min(buckets[f], Math.floor(k / f));
remaining -= take;
k -= take * f;
if (take < buckets[f]) break;
}
return remaining;
}Edge cases to test
- k = 0 (nothing removed, answer is the number of distinct values)
- k = arr.length (everything removed, answer 0)
- All values equal
- All values distinct
- k is just short of finishing off the next value (leftover removals are wasted on a partial value)
Hints
Hint 1
Removing part of a value's copies never lowers the distinct count. Only fully erased values matter.
Hint 2
To erase as many values as possible with a fixed budget, erase the cheapest ones first: the values with the smallest frequency.
FAQ
What is the best time complexity for Least Number of Unique Integers after K Removals?
Optimal (bucket by frequency) runs in O(n) time and O(n) extra space. Counting, filling the buckets and the walk over frequencies 1..n are each linear.
Which pattern does Least Number of Unique Integers after K Removals use?
It is a heaps problem that uses the top k / kth largest / smallest pattern. Other problems with the same pattern: Kth Largest Element in an Array, Kth Largest Element in a Stream, Top K Frequent Words.
Is there a brute force solution for Least Number of Unique Integers after K Removals?
Yes. Min-heap of frequencies takes O(n + d log d) time and O(d) space. Count each value, push all frequencies into a min-heap, then keep popping the smallest frequency while the budget k can pay for it.
Which edge cases should I test for Least Number of Unique Integers after K Removals?
k = 0 (nothing removed, answer is the number of distinct values); k = arr.length (everything removed, answer 0); All values equal; All values distinct; k is just short of finishing off the next value (leftover removals are wasted on a partial value).