Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in Rust: O(n) with HashMap and Bucket Sort

Practice O(n) Read the full explanation

You get an array 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

    RUST · HASH TABLE

    Top K Frequent Elements in Rust, explained

    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

    1. Declare count as a mutable HashMap<i32, usize> created with HashMap::new(). The file already starts with use std::collections::HashMap;. It maps each value to how many times it appears.
    2. Loop over &nums with the pattern &num. Borrowing keeps nums usable afterwards, and the pattern copies each i32 out of its reference.
    3. Increment the count with *count.entry(num).or_insert(0) += 1. The entry is looked up once; a new key starts at 0.
    4. Declare buckets as a Vec<Vec<i32>> of nums.len() + 1 empty vectors. The extra one makes index nums.len() valid.
    5. Loop over count taking each entry as (num, freq).
    6. Push num onto buckets[freq].
    7. Declare result as an empty Vec<i32>.
    8. Declare freq as a mutable variable starting at nums.len(), the highest possible count.
    9. Loop while result.len() < k as usize. The cast is needed because Rust compares only numbers of the same type.
    10. Add the bucket buckets[freq] to result with extend_from_slice, passing a reference.
    11. Move down one count with freq -= 1.
    12. Return result as 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 for num, and or_insert(0) returns a &mut usize to its value, inserting 0 first if the key is new. The * dereferences that mutable reference so += 1 changes the stored count. This replaces the "check, then insert, then update" dance with one lookup.
    • Counts are usize. They index buckets, and indexes in Rust are always usize.
    • vec![Vec::new(); nums.len() + 1] clones the empty vector for every slot, so each bucket is its own vector. The element type must be Clone, which Vec<i32> is.
    • Iterating the map by value. for (num, freq) in count consumes the map and yields owned (key, value) pairs. The map isn't needed afterwards, so nothing is lost. The iteration order of a HashMap is 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 a usize and k an i32, so the comparison needs the cast. For a valid k (at least 1) the cast keeps its value.
    • freq -= 1 on a usize. Going below 0 would wrap in an optimized build and panic in a debug build. With valid input it can't happen: k is at most the number of distinct values, so the result fills up before the walk runs out of buckets.
    • extend_from_slice copies 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] with k = 1 gives [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] with k = 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 + 1 on the bucket count. A value that appears in every position of nums has count nums.len(). With only nums.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] with k = 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 past k, 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 = 2 gives [1, 2].
    • nums = [1], k = 1 gives [1].
    • nums = [4, -1, 4, -1, 7, 4, -1, 9], k = 2 gives [-1, 4].
    • nums = [5, 5, 5, 5, 3, 3, 3, 8, 8, 1], k = 1 gives [5].
    • nums = [-7, -7, 2, 2, 2, 0], k = 2 gives [-7, 2].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free