Solution: Least Number of Unique Integers after K Removals
Let’s solve the Least Number of Unique Integers after K Removals problem using the Top K Elements pattern.
We'll cover the following
Statement
You are given an integer array, arr
, and an integer, k
. Your task is to remove exactly k
elements from the array so that the number of distinct integers remaining in the array is minimized. Determine the minimum possible count of unique integers after the removals.
Constraints:
arr.length
arr[i]
k
arr.length
Solution
The solution’s core idea is to reduce the number of unique integers by always removing the least frequent elements first. When we want to minimize the number of unique values remaining after deleting a fixed number of elements, it makes sense to first eliminate those integers that occur less frequently.
This strategy relies on two key observations:
We should first target the smallest frequency groups to minimize the remaining unique integers because they require fewer removals to eliminate a whole unique integer.
Using a structure that quickly gives us the smallest frequency at each step, such as a min‑heap, allows us to plan quick deletions.
To apply the above intuition, we start by counting how many times each distinct element appears in the array. These counts are placed in a min heap, which lets us access and remove the smallest counts first. Removing numbers that appear the least reduces the variety with minimal deletions, so we repeatedly remove the smallest counts until we use up to k removals. If we reach a count that we can’t fully remove without exceeding k, the remaining heap size plus one gives the number of unique integers left. We stop at that point because any remaining counts directly represent the unique integers left. This approach follows the core intuition by always targeting the most efficient removals first.
Now, let’s look at the solution steps below:
Create a frequency
map
from each integer inarr
.Convert all frequency values in
map
into a min heap,frequencies
. This allows instant access to the smallest frequency group at each step.Initialize a
counter
tofor removals. It keeps track of how many elements we have deleted so far. Next, traverse all frequencies in ascending order and repeatedly:
Remove the smallest frequency from
frequencies
.Add that frequency to
counter
(representing removing all occurrences of that integer).After each removal, check if
counter
exceedsk
.If yes, we cannot fully remove that group, so the current heap size plus one gives the count of unique integers left. We return this count as the number of unique integers left after
k
removals.
After traversal, if all frequencies are removed without exceeding
k
, return, showing that no unique integers are left.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.