Start learning free

LESSON 85 OF 321 · HASH TABLE

Top K Frequent Elements in C++: Bucket Sort in O(n)

Practice O(n) Read the full explanation

You get a vector of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 12
    Ctrl + Enter to check

    C++ · HASH TABLE

    Top K Frequent Elements in C++, explained

    Problem overview

    The method topKFrequent takes a vector<int> named nums and an integer k, and returns the k values that appear most often in nums, in any order. The frequency of a value is how many times it appears. The answer is guaranteed to be unique: every value in it appears more often than every value left out, so there is no tie at the cut-off.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears three times, 2 appears twice and 3 once, so the answer is [1, 2]. For [4, -1, 4, -1, 7, 4, -1, 9] and k = 2, the values 4 and -1 appear three times each and 7 and 9 once, so the answer holds 4 and -1. The statement asks for O(n) time and O(n) extra space.

    Approach: count, then bucket by count

    The first half is the same for every solution: count the occurrences of each value in one pass with a hash table.

    The second half is choosing the k largest counts. The straightforward way is to sort the distinct values by count, which costs O(n log n). A heap of size k costs O(n log k). To reach O(n), use the fact that a count can't exceed n, the length of nums. That lets you skip comparisons and use bucket sort: make a list of buckets numbered 0 to n, and put each value into the bucket whose number is its count. The values that appear exactly f times end up in buckets[f].

    Then walk the buckets from the highest index down, collecting values until you have k of them. Total work: one pass to count, one to fill the buckets, and a walk over at most n + 1 buckets.

    For [1, 1, 1, 2, 2, 3], the buckets end up as follows (the other buckets are empty):

    Bucket (count)Values
    13
    22
    31

    Walking down from the top, the first non-empty bucket is 3, giving the value 1, and the next is 2, giving the value 2. That is k = 2 values, so the walk stops.

    Step by step

    1. Declare count as an unordered_map<int, int>, mapping each value to the number of times it appears.
    2. Loop over every int num in nums with a range-based for.
    3. Do count[num]++. The [] operator inserts a missing key with value 0, so a value seen for the first time goes from 0 to 1.
    4. Create buckets, a vector<vector<int>> with nums.size() + 1 empty vectors. Counts run from 1 to nums.size(), so that last index must exist.
    5. Loop over the entries of count with auto [num, freq], which unpacks each pair into the value and its count.
    6. Add num to buckets[freq] with push_back. No counts are compared with each other.
    7. Declare result, a vector<int> for the answer.
    8. Declare freq as an int starting at nums.size(), the highest count any value could have.
    9. Loop while result.size() < k. Each pass takes one bucket.
    10. Append the whole bucket with result.insert(result.end(), buckets[freq].begin(), buckets[freq].end()). Inserting a range in front of end() adds it at the back. The answer is unique, so a bucket never pushes result past k values.
    11. Decrement freq to move to the next lower count.
    12. Return result.

    The solution in C++

    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> count;
            for (int num : nums) {
                count[num]++;
            }
            vector<vector<int>> buckets(nums.size() + 1);
            for (auto [num, freq] : count) {
                buckets[freq].push_back(num);
            }
            vector<int> result;
            int freq = nums.size();
            while (result.size() < k) {
                result.insert(result.end(), buckets[freq].begin(), buckets[freq].end());
                freq--;
            }
            return result;
        }
    };
    

    The C++ details worth knowing:

    • map[key] inserts. Reading count[num] for a missing key adds it with the default value 0. That is exactly what makes count[num]++ work as a counter. When you only want to ask whether a key exists, use count.find(key) or count.count(key), which don't insert anything.
    • Parentheses, not braces, for the bucket count. vector<vector<int>> buckets(nums.size() + 1) builds that many empty inner vectors. Because the indices are the counts, buckets[freq] is always valid for freq up to nums.size().
    • auto [num, freq] is a structured binding, available since C++17. Each element of an unordered_map<int, int> is a pair, and the brackets name its two parts. for (auto ...) copies each pair, which is cheap for two ints.
    • Two variables named freq. The one in the structured binding lives only inside that loop. The int freq declared afterwards is a separate variable, and the compiler accepts this because the first one is out of scope by then.
    • Order is not specified. An unordered_map visits its entries in an unspecified order, so the values inside one bucket can appear in any order, and so can the result when a bucket holds several values. The problem accepts any order.
    • Signed and unsigned. result.size() is unsigned and k is an int. The comparison works for the positive k the constraints guarantee. Compilers may warn about comparing the two.

    Complexity

    Time is O(n). Counting is one pass over nums. Filling the buckets visits each distinct value once, which is at most n values. The walk visits at most n buckets and copies at most k values in total.

    Extra space is O(n). The map holds at most n entries and there are n + 1 buckets, which together hold at most n values.

    Edge cases and common mistakes

    • A single element. nums = [1] with k = 1 returns [1]. The walk starts at bucket 1, which holds the value.
    • Negative values. They are fine as map keys. The values are never used as indices, only the counts are. A solution that counted into an array indexed by value would need an offset.
    • All values distinct. [1, 2, 3] with k = 3 has every value in bucket 1. The walk passes the empty upper buckets and takes all three values from bucket 1.
    • Starting the walk too low. Starting freq at nums.size() - 1 would miss the case where one value fills the whole vector, such as [5, 5, 5]. That is why the buckets run up to nums.size().
    • Making the buckets one slot short. A vector of nums.size() buckets has no index nums.size(), and writing there is undefined behaviour.
    • Expecting a particular order. For [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, sorted, the answer is [-1, 4]. The raw order from the function can be either way round, and both are correct.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free