Least Number of Unique Integers after K Removals

medium array hash map greedy sorting counting

Problem

Given arr and k, return the least number of unique integers left in the array after removing exactly k elements.

Inputarr=[4,3,1,1,3,3,2], k=3
Output2
Remove all 4 and 2 (cost 1+1=2), then one more 1 → uniques {1,3} remain.

from collections import Counter
def find_least_num_of_unique_ints(arr, k):
    freq = sorted(Counter(arr).values())
    uniques = len(freq)
    for c in freq:
        if k >= c: k -= c; uniques -= 1
        else: break
    return uniques
function findLeastNumOfUniqueInts(arr, k) {
  const f = {}; for (const x of arr) f[x] = (f[x] || 0) + 1;
  const freq = Object.values(f).sort((a, b) => a - b);
  let u = freq.length;
  for (const c of freq) {
    if (k >= c) { k -= c; u--; } else break;
  }
  return u;
}
class Solution {
    public int findLeastNumOfUniqueInts(int[] arr, int k) {
        Map f = new HashMap<>();
        for (int x : arr) f.merge(x, 1, Integer::sum);
        List freq = new ArrayList<>(f.values());
        Collections.sort(freq);
        int u = freq.size();
        for (int c : freq) { if (k >= c) { k -= c; u--; } else break; }
        return u;
    }
}
int findLeastNumOfUniqueInts(vector& arr, int k) {
    unordered_map f;
    for (int x : arr) f[x]++;
    vector freq;
    for (auto& p : f) freq.push_back(p.second);
    sort(freq.begin(), freq.end());
    int u = freq.size();
    for (int c : freq) { if (k >= c) { k -= c; u--; } else break; }
    return u;
}
Time: O(n log n) Space: O(n)