Least Number of Unique Integers after K Removals

Drop the rarest integers first — sort frequencies ascending and consume the budget.

Medium
Time O(n log n) Space O(n)
LeetCode
3 min read
top-k greedy hash-map

Problem#

Remove exactly k elements from arr so the number of distinct remaining values is minimized. Return that count.

Examples#

  • arr = [5,5,4], k = 11
  • arr = [4,3,1,1,3,3,2], k = 32

Constraints#

  • 1 <= arr.length <= 10^5.

Approach#

Sort frequencies ascending. Eliminate the rarest values first — each one removed eliminates one distinct value if we cover its full count. Sum frequencies left-to-right; when the running sum exceeds k, the remaining number of frequencies is the answer.

Solution#

Least Unique Integers After K Removals
class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int,int> freq;
for (int x : arr) ++freq[x];
vector<int> counts;
for (auto& [_, c] : freq) counts.push_back(c);
sort(counts.begin(), counts.end());
int removed = 0, i = 0;
while (i < (int)counts.size() && removed + counts[i] <= k) {
removed += counts[i++];
}
return counts.size() - i;
}
};

Editorial#

Greedy is optimal: removing all occurrences of the rarest value uses the fewest of our k removals per distinct-value eliminated. Sorting frequencies and consuming left-to-right is the direct realization.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.