Least Number of Unique Integers after K Removals

Medium Heaps Top K / Kth Largest / Smallest

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^5
  • 1 <= arr[i] <= 10^9
  • 0 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
Min-heap of frequenciesO(n + d log d)O(d)
Optimal (bucket by frequency)O(n)O(n)

1Min-heap of frequencies

TimeO(n + d log d)Counting is linear; each of the d distinct values is pushed and popped at most once.
SpaceO(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.

  1. Count occurrences with a hash map.
  2. Push every count into a min-heap.
  3. While the heap is not empty and its top is <= k: k -= top, pop.
  4. 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();
    }
}

2Optimal (bucket by frequency)

TimeO(n)Counting, filling the buckets and the walk over frequencies 1..n are each linear.
SpaceO(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.

  1. Count occurrences; let remaining = number of distinct values.
  2. buckets[f] = how many values occur exactly f times.
  3. For f = 1..n: take = min(buckets[f], k / f); remaining -= take; k -= take * f.
  4. If take < buckets[f], the budget cannot erase another value of this or any larger frequency, so stop.
  5. 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;
    }
}

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