Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in Go: O(n) with 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

    GO · HASH TABLE

    Top K Frequent Elements in Go, explained

    Problem overview

    The function topKFrequent receives a slice of integers, 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 the number of times it appears. The answer is guaranteed to be unique: every value in it appears more times than every value left out, so there is no tie at the cut.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears 3 times, 2 appears twice and 3 once, so the answer is [1, 2]. With nums = [4, -1, 4, -1, 7, 4, -1, 9] and k = 2, 4 and -1 both appear 3 times and 7 and 9 once, so the answer is 4 and -1, in either order.

    The budget is O(n) time and O(n) extra space, where n is the length of nums.

    Approach: count, then bucket by count

    Counting is the easy part: one pass over nums with a map from each value to how many times it appears. The question is how to pick the k largest counts. Sorting the distinct values by count takes O(n log n), which is over the budget.

    The way around it is that a count can't be larger than len(nums). So instead of comparing counts, put each value straight into a bucket for its count: buckets[f] holds the values that appear exactly f times. This is a bucket sort, and it never compares two counts with each other.

    Then read the buckets from the highest count down, adding their values to the result until it holds k values. Most buckets are empty, and the walk visits at most len(nums) of them, so it stays linear.

    For [1, 1, 1, 2, 2, 3], the counts are 1 for three times, 2 for twice and 3 for once. Bucket 3 holds [1], bucket 2 holds [2] and bucket 1 holds [3]. Walking down from bucket 6 reaches bucket 3 first, then bucket 2, and with k = 2 the result is [1, 2].

    Step by step

    1. Create the count map as make(map[int]int). It maps each value to the number of times it appears.
    2. Loop over nums with range, ignoring the index with _.
    3. Add 1 to count[num] with ++. A missing key reads as 0, so a first sighting goes from 0 to 1.
    4. Create buckets as a [][]int of length len(nums)+1. The counts run from 1 to len(nums), so index len(nums) must exist.
    5. Loop over count with range, getting each value as num and its count as freq.
    6. Append num to buckets[freq] and store the grown slice back in buckets[freq].
    7. Create result as an empty []int.
    8. Start freq at len(nums), the highest count a value can have. We don't know which buckets are full, so we start at the top and walk down.
    9. Loop while len(result) < k.
    10. Append the whole bucket buckets[freq] to result with ... after it, and store the new slice back in result.
    11. Decrement freq to move to the next lower count.
    12. Return result.

    The solution in Go

    func topKFrequent(nums []int, k int) []int {
        count := make(map[int]int)
        for _, num := range nums {
            count[num]++
        }
        buckets := make([][]int, len(nums)+1)
        for num, freq := range count {
            buckets[freq] = append(buckets[freq], num)
        }
        result := []int{}
        freq := len(nums)
        for len(result) < k {
            result = append(result, buckets[freq]...)
            freq--
        }
        return result
    }
    

    The Go details worth a closer look:

    • Missing map keys read as zero. count[num]++ works on a key that isn't in the map yet, because reading it gives the zero value, 0. No if or v, ok := m[k] check is needed for counting. A count[99] on a map without 99 gives 0 without an error.
    • Nil slices work with append. make([][]int, len(nums)+1) creates the outer slice, and each inner slice starts as nil with length 0. append(buckets[freq], num) allocates the inner slice when it is needed, so no bucket has to be created by hand.
    • append returns the slice, so the result is stored back: buckets[freq] = append(buckets[freq], num).
    • append(result, buckets[freq]...) adds all the items of a slice. Without the ..., Go would try to add the slice itself as one element, which is a compile error for a []int.
    • Map iteration order is not specified. The range over count may visit the values in any order, and the order can change from one run to the next. That only affects the order inside a bucket, and the problem accepts the answer in any order.
    • Go's while loop. for len(result) < k { ... } is a for with only a condition.

    Complexity

    Time: O(n). Counting is one pass. Filling the buckets visits each distinct value once, and there are at most n of them. Reading the buckets visits at most len(nums) of them, plus the values it copies.

    Space: O(n). The map holds at most n entries, the bucket slice has len(nums)+1 entries, and the values stored in the buckets are at most n in total.

    Edge cases and common mistakes

    • One value. [1] with k = 1 gives [1]. The buckets slice has two entries, and bucket 1 holds the value.
    • One value repeated. [5, 5, 5, 5] with k = 1 gives [5]. The value goes to bucket 4, the top one.
    • k equals the number of distinct values. [1, 2, 3] with k = 3 gives [1, 2, 3] in some order: all three sit in bucket 1.
    • Negative values. The values are keys of the map, not indices, so -1 is fine. Only the counts are used as indices.
    • A bucket that overshoots k. The loop adds a whole bucket at a time. Because the answer is unique, a bucket never takes the result past k values: that would mean a tie at the cut. For [1, 1, 2, 2, 3] with k = 1, that tie exists, so the input is outside the lesson's guarantee, and the function would return both 1 and 2.
    • Making buckets one too short. With length len(nums), a value that fills the whole slice has no bucket at index len(nums), and the program panics.
    • Forgetting the ... in the final append, which the compiler rejects.

    Testing

    • nums = [1, 1, 1, 2, 2, 3], k = 2 gives [1, 2].
    • nums = [1, 1, 1, 2, 2, 3], k = 1 gives [1].
    • nums = [1, 1, 1, 2, 2, 3], k = 3 gives [1, 2, 3].
    • nums = [1], k = 1 gives [1].
    • nums = [4, -1, 4, -1, 7, 4, -1, 9], k = 2 gives [4, -1] or [-1, 4]: both are correct.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free