← Home

1481. Least Number of Unique Integers after K Removals

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
148

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1481. Least Number of Unique Integers after K Removals, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue, greedy.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findLeastNumOfUniqueInts, vcounter.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 1172 ms, faster than 20.00% of C++ online submissions for Least Number of Unique Integers after K Removals.
02//Memory Usage: 106.5 MB, less than 20.00% of C++ online submissions for Least Number of Unique Integers after K Removals.
03class Solution {
04public:
05    int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
06        unordered_map<int, int> counter;
07        
08        for(int& num : arr){
09            counter[num] += 1;
10        }
11        
12        vector<vector<int>> vcounter;
13        for(auto it = counter.begin(); it != counter.end(); it++){
14            vcounter.push_back({it->first, it->second});
15        }
16        
17        //the smaller count, the earlier be popped
18        auto comp = [](const vector<int>& p, const vector<int>& q){
19            return p[1] > q[1];
20        };
21        
22        priority_queue<vector<int>, vector<vector<int>>, decltype(comp)> pq(vcounter.begin(), vcounter.end(), comp);
23        
24        while(!pq.empty() && k > 0){
25            vector<int> p = pq.top(); pq.pop();
26            if(k < p[1]){
27                pq.push({p[0], p[1]-k});
28            }
29            k -= p[1];
30        }
31        
32        return pq.size();
33    }
34};
35
36//sort
37//https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/discuss/686376/Simple-C%2B%2B-O(N-log-N)-VIDEO-SOL
38//Runtime: 444 ms, faster than 20.00% of C++ online submissions for Least Number of Unique Integers after K Removals.
39//Memory Usage: 61.2 MB, less than 100.00% of C++ online submissions for Least Number of Unique Integers after K Removals.
40class Solution {
41public:
42    int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
43        unordered_map<int, int> counter;
44        
45        for(int& num : arr){
46            counter[num] += 1;
47        }
48        
49        //the actual number is not important, we only care their counts!
50        vector<int> vcounter(counter.size());
51        int i = 0;
52        for(auto it = counter.begin(); it != counter.end(); it++){
53            vcounter[i++] = it->second;
54        }
55        
56        //the smaller count, the earlier be processed
57        sort(vcounter.begin(), vcounter.end());
58        
59        // for(int e : vcounter){
60        //     cout << e << " ";
61        // }
62        // cout << endl;
63        
64        for(i = 0; i < vcounter.size() && k > 0; ){
65            if(k >= vcounter[i]){
66                k -= vcounter[i];
67                i++;
68            }else{
69                k = 0;
70                /*
71                vcounter[i] is not completely used,
72                so don't increase i
73                */
74            }
75        }
76        
77        /*
78        [0,i-1] is the removed elements,
79        [i, vcounter.size()-1] is the remaining elements,
80        remaining elements' count is vcounter.size()-i
81        */
82        return (vcounter.size() - i);
83    }
84};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.