Problem overview
The function top_k_frequent receives a vector of integers, nums, and an integer k. It returns the k values that appear most often in nums, in any order. A value's frequency is the number of times it appears. The answer is guaranteed to be unique: every returned value appears more often than every value left out, so there are no ties at the cut. The budget is O(n) time and O(n) space.
For nums = [1, 1, 1, 2, 2, 3] and k = 2, 1 appears three times, 2 twice and 3 once, so the answer is 1 and 2. For [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 both appear three times, and either [4, -1] or [-1, 4] is correct.
Approach: count, then bucket by count
The first step is natural: count every value with a hash map in one pass, O(n). The second step is where the naive solution loses time. Sorting the distinct values by count takes O(n log n), and the problem asks for linear time.
The way out is that a count is a small, bounded number. No value can appear more than nums.len() times, so there are only nums.len() + 1 possible counts, 0 to n. Make one bucket per count and drop each value into the bucket for its count: buckets[f] holds the values that appear exactly f times. No comparisons are needed, because each value goes straight to its place. This is a bucket sort.
To collect the answer, start at the highest bucket and walk down, adding the contents of each bucket, until the result holds k values. Empty buckets cost nothing but one step each, and there are at most n buckets, so the walk is O(n).
For [1, 1, 1, 2, 2, 3] the buckets, indexed from 0 to 6, are:
[[], [3], [2], [1], [], [], []]
Bucket 1 holds 3, bucket 2 holds 2 and bucket 3 holds 1. Walking down from index 6, the first non-empty bucket gives 1 and the next gives 2, which makes k = 2 values.
Step by step
- Declare
countas a mutableHashMap<i32, usize>created withHashMap::new(). The file already starts withuse std::collections::HashMap;. It maps each value to how many times it appears. - Loop over
&numswith the pattern&num. Borrowing keepsnumsusable afterwards, and the pattern copies eachi32out of its reference. - Increment the count with
*count.entry(num).or_insert(0) += 1. The entry is looked up once; a new key starts at 0. - Declare
bucketsas aVec<Vec<i32>>ofnums.len() + 1empty vectors. The extra one makes indexnums.len()valid. - Loop over
counttaking each entry as(num, freq). - Push
numontobuckets[freq]. - Declare
resultas an emptyVec<i32>. - Declare
freqas a mutable variable starting atnums.len(), the highest possible count. - Loop while
result.len() < k as usize. The cast is needed because Rust compares only numbers of the same type. - Add the bucket
buckets[freq]toresultwithextend_from_slice, passing a reference. - Move down one count with
freq -= 1. - Return
resultas the last expression.
The solution in Rust
use std::collections::HashMap;
impl Solution {
fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut count: HashMap<i32, usize> = HashMap::new();
for &num in &nums {
*count.entry(num).or_insert(0) += 1;
}
let mut buckets: Vec<Vec<i32>> = vec![Vec::new(); nums.len() + 1];
for (num, freq) in count {
buckets[freq].push(num);
}
let mut result: Vec<i32> = Vec::new();
let mut freq = nums.len();
while result.len() < k as usize {
result.extend_from_slice(&buckets[freq]);
freq -= 1;
}
result
}
}
The Rust details worth a closer look:
- The entry API.
count.entry(num)finds the slot fornum, andor_insert(0)returns a&mut usizeto its value, inserting 0 first if the key is new. The*dereferences that mutable reference so+= 1changes the stored count. This replaces the "check, then insert, then update" dance with one lookup. - Counts are
usize. They indexbuckets, and indexes in Rust are alwaysusize. vec![Vec::new(); nums.len() + 1]clones the empty vector for every slot, so each bucket is its own vector. The element type must beClone, whichVec<i32>is.- Iterating the map by value.
for (num, freq) in countconsumes the map and yields owned(key, value)pairs. The map isn't needed afterwards, so nothing is lost. The iteration order of aHashMapis unspecified and can change between runs, which is why values inside one bucket may come out in any order. The problem allows any order. k as usize.result.len()is ausizeandkani32, so the comparison needs the cast. For a validk(at least 1) the cast keeps its value.freq -= 1on ausize. Going below 0 would wrap in an optimized build and panic in a debug build. With valid input it can't happen:kis at most the number of distinct values, so the result fills up before the walk runs out of buckets.extend_from_slicecopies the items of a slice onto the end of the vector.&buckets[freq]is a&Vec<i32>, which Rust coerces to the slice it expects.
Complexity
Time: O(n). Counting is one pass with constant-time map operations on average. Filling the buckets visits each distinct value once, and the walk down from n visits at most n buckets and copies at most k values.
Space: O(n). The map holds one entry per distinct value, and the buckets hold n + 1 vectors with those same values spread across them.
Edge cases and common mistakes
- A single element.
[1]withk = 1gives[1]: the one value lands in bucket 1, and the walk starts at 1. - Ties inside the answer. In
[4, -1, 4, -1, 7, 4, -1, 9]withk = 2, the values 4 and -1 share bucket 3 and both are returned together, in whatever order the map produced them. - Negative values. The values are only keys of the map, never indexes, so negative numbers need no care. The indexes are the counts, and those are never negative.
- Forgetting the
+ 1on the bucket count. A value that appears in every position ofnumshas countnums.len(). With onlynums.len()buckets,buckets[freq]would be out of range and panic. This is the case for[1]. - Assuming an order. The result isn't sorted and doesn't follow the input order. Sort a copy of it if you want to compare it with an expected answer: for
[5, 5, 5, 5, 3, 3, 3, 8, 8, 1]withk = 3, the sorted result is[3, 5, 8]. - Sorting by count instead. Collecting the map's pairs and sorting them by count also works, in
O(n log n), but the lesson aims for linear time. - Overshooting
k. If a bucket put the result pastk, there would be a tie at the cut, and the guarantee of a unique answer rules that out. Extending by whole buckets is therefore safe here.
Testing
The results are listed sorted, since the function may return them in any order.
nums = [1, 1, 1, 2, 2, 3],k = 2gives[1, 2].nums = [1],k = 1gives[1].nums = [4, -1, 4, -1, 7, 4, -1, 9],k = 2gives[-1, 4].nums = [5, 5, 5, 5, 3, 3, 3, 8, 8, 1],k = 1gives[5].nums = [-7, -7, 2, 2, 2, 0],k = 2gives[-7, 2].
