Least Number of Unique Integers after K Removals Problem
Description
LeetCode Problem 1481.
Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements**.**
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
Constraints:
1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.length
Solution
Approach: Greedy, Rarest Values First
A distinct value disappears only when all of its copies are removed. To make as many values disappear as possible with exactly k removals, we should spend the removals on the values that have the fewest copies first: removing a value that appears 2 times costs less than one that appears 5 times, and both reduce the count by one.
So we count how often each value appears, sort these counts in increasing order, and subtract them from k one by one:
- if
kstays>= 0, that value is gone completely; - as soon as
kbecomes negative, the current value cannot be fully removed, and neither can any value after it (they are at least as frequent). The answer is the number of values from this one to the end.
If we get through all the counts, every value was removed and the answer is 0.
Removals left over at the end of a value (when k becomes negative) are spent on copies of that value, so the total is still exactly k, and it does not change the answer.
Complexity: O(n log n) time for sorting the counts and O(n) extra space for the counter.
from collections import Counter
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
counts = sorted(Counter(arr).values()) # rarest values first
for i, c in enumerate(counts):
k -= c
if k < 0: # cannot remove all copies of counts[i]
return len(counts) - i
return 0