To minimize the number of unique integers after removing k elements, we should prioritize removing integers that appear least frequently. By eliminating all occurrences of the rarest integers first, we reduce the unique count most efficiently. Sorting frequencies in ascending order lets us greedily remove elements starting from the smallest frequency.
k is large enough to remove all occurrences of this integer, subtract the frequency from k and decrease the unique count.0.A min-heap naturally gives us access to the smallest frequency first. Instead of sorting all frequencies upfront, we can repeatedly extract the minimum frequency and try to remove that integer. This approach works similarly to sorting but uses a heap data structure for extraction.
k > 0 and the heap is not empty:k can cover this frequency, subtract it from k and decrement the result count.Since frequencies are bounded by the array length, we can use bucket sort to avoid comparison-based sorting. We create buckets where bucket f contains the count of integers with frequency f. Then we iterate through buckets from frequency 1 upward, removing as many complete integers as possible at each frequency level.
freqList[f] counts how many integers have frequency f.f from 1 to the array length:f can be fully removed given the remaining k.k and reduce the result count.k cannot remove all integers at this frequency, compute partial removal and break.class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
freq = Counter(arr)
freq_list = [0] * (len(arr) + 1)
for n, f in freq.items():
freq_list[f] += 1
res = len(freq)
for f in range(1, len(freq_list)):
remove = freq_list[f]
if k >= f * remove:
k -= f * remove
res -= remove
else:
remove = k // f
res -= remove
break
return resThe greedy strategy requires removing elements with the lowest frequency first to maximize the reduction in unique count. Removing high-frequency elements wastes removals since you need more deletions to eliminate a single unique integer. Always sort frequencies in ascending order.
A subtle bug is decrementing the unique count even when you cannot fully remove all occurrences of an integer. If k is less than the current frequency, you cannot eliminate that unique integer, so the count should not decrease. Only reduce the unique count when all occurrences are removed.
When k cannot fully cover the current frequency but can partially cover it, some implementations incorrectly skip this case entirely. While partial removal does not reduce the unique count, you still need to account for it when moving to the next frequency bucket in bucket sort approaches.