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 |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
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
- Declare
countas anunordered_map<int, int>, mapping each value to the number of times it appears. - Loop over every
int numinnumswith a range-basedfor. - 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. - Create
buckets, avector<vector<int>>withnums.size() + 1empty vectors. Counts run from 1 tonums.size(), so that last index must exist. - Loop over the entries of
countwithauto [num, freq], which unpacks each pair into the value and its count. - Add
numtobuckets[freq]withpush_back. No counts are compared with each other. - Declare
result, avector<int>for the answer. - Declare
freqas anintstarting atnums.size(), the highest count any value could have. - Loop while
result.size() < k. Each pass takes one bucket. - Append the whole bucket with
result.insert(result.end(), buckets[freq].begin(), buckets[freq].end()). Inserting a range in front ofend()adds it at the back. The answer is unique, so a bucket never pushesresultpastkvalues. - Decrement
freqto move to the next lower count. - 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. Readingcount[num]for a missing key adds it with the default value 0. That is exactly what makescount[num]++work as a counter. When you only want to ask whether a key exists, usecount.find(key)orcount.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 forfrequp tonums.size(). auto [num, freq]is a structured binding, available since C++17. Each element of anunordered_map<int, int>is a pair, and the brackets name its two parts.for (auto ...)copies each pair, which is cheap for twoints.- Two variables named
freq. The one in the structured binding lives only inside that loop. Theint freqdeclared 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_mapvisits 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 andkis anint. The comparison works for the positivekthe 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]withk = 1returns[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]withk = 3has 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
freqatnums.size() - 1would miss the case where one value fills the whole vector, such as[5, 5, 5]. That is why the buckets run up tonums.size(). - Making the buckets one slot short. A vector of
nums.size()buckets has no indexnums.size(), and writing there is undefined behaviour. - Expecting a particular order. For
[4, -1, 4, -1, 7, 4, -1, 9]withk = 2, sorted, the answer is[-1, 4]. The raw order from the function can be either way round, and both are correct.
