1481. Least Number of Unique Integers after K Removal - Explanation
Description
Remove exactly k elements from arr. Return the smallest number of distinct integer values that can remain. Removing an element removes only that occurrence, and the removed positions do not need to be consecutive.
Example 1:
Input: arr = [1,1,2,3]
k = 2
Output: 1Explanation: Remove the single occurrences of 2 and 3. Only the value 1 remains, so the answer is 1.
Example 2:
Input: arr = [7,7,8]
k = 0
Output: 2Explanation: No elements may be removed. The remaining distinct values are 7 and 8, giving 2.
Example 3:
Input: arr = [4,5]
k = 2
Output: 0Explanation: Remove both elements. The empty array contains zero distinct values.
Constraints:
1 <= arr.length <= 1000001 <= arr[i] <= 10000000000 <= k <= arr.length
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Maps - Counting element frequencies efficiently using key-value data structures
- Sorting - Understanding how to sort arrays and the time complexity implications
- Greedy Algorithms - Making locally optimal choices (removing least frequent elements first) to achieve a global optimum
- Heaps/Priority Queues - For the min-heap approach, understanding how to efficiently extract minimum values
1. Sorting
Intuition
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.
Algorithm
- Count the frequency of each integer using a hash map.
- Extract the frequency values and sort them in ascending order.
- Iterate through the sorted frequencies:
- If
kis large enough to remove all occurrences of this integer, subtract the frequency fromkand decrease the unique count. - Otherwise, we cannot fully remove this integer, so return the remaining unique count.
- If
- If all integers can be removed, return
0.
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Min-Heap
Intuition
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.
Algorithm
- Build a frequency map of all integers.
- Insert all frequency values into a min-heap.
- While
k > 0and the heap is not empty:- Pop the smallest frequency.
- If
kcan cover this frequency, subtract it fromkand decrement the result count. - Otherwise, stop (we cannot fully remove this integer).
- Return the remaining unique count.
Time & Space Complexity
- Time complexity:
- Space complexity:
3. Bucket Sort
Intuition
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.
Algorithm
- Build a frequency map of all integers.
- Create a frequency list (bucket array) where
freqList[f]counts how many integers have frequencyf. - Iterate
ffrom1to the array length:- Calculate how many integers with frequency
fcan be fully removed given the remainingk. - Subtract the cost from
kand reduce the result count. - If
kcannot remove all integers at this frequency, compute partial removal and break.
- Calculate how many integers with frequency
- Return the remaining unique count.
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 resTime & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Removing High-Frequency Elements First
The 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.
Counting Unique Integers Incorrectly
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.
Forgetting Partial Removal Logic
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.
Sign in to join the discussion