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
- Create the
countmap asmake(map[int]int). It maps each value to the number of times it appears. - Loop over
numswithrange, ignoring the index with_. - Add 1 to
count[num]with++. A missing key reads as 0, so a first sighting goes from 0 to 1. - Create
bucketsas a[][]intof lengthlen(nums)+1. The counts run from 1 tolen(nums), so indexlen(nums)must exist. - Loop over
countwithrange, getting each value asnumand its count asfreq. - Append
numtobuckets[freq]and store the grown slice back inbuckets[freq]. - Create
resultas an empty[]int. - Start
freqatlen(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. - Loop while
len(result) < k. - Append the whole bucket
buckets[freq]toresultwith...after it, and store the new slice back inresult. - Decrement
freqto move to the next lower count. - 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. Noiforv, ok := m[k]check is needed for counting. Acount[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 asnilwith length 0.append(buckets[freq], num)allocates the inner slice when it is needed, so no bucket has to be created by hand. appendreturns 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
rangeovercountmay 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 aforwith 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]withk = 1gives[1]. The buckets slice has two entries, and bucket 1 holds the value. - One value repeated.
[5, 5, 5, 5]withk = 1gives[5]. The value goes to bucket 4, the top one. kequals the number of distinct values.[1, 2, 3]withk = 3gives[1, 2, 3]in some order: all three sit in bucket 1.- Negative values. The values are keys of the map, not indices, so
-1is 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 pastkvalues: that would mean a tie at the cut. For[1, 1, 2, 2, 3]withk = 1, that tie exists, so the input is outside the lesson's guarantee, and the function would return both 1 and 2. - Making
bucketsone too short. With lengthlen(nums), a value that fills the whole slice has no bucket at indexlen(nums), and the program panics. - Forgetting the
...in the final append, which the compiler rejects.
Testing
nums = [1, 1, 1, 2, 2, 3],k = 2gives[1, 2].nums = [1, 1, 1, 2, 2, 3],k = 1gives[1].nums = [1, 1, 1, 2, 2, 3],k = 3gives[1, 2, 3].nums = [1],k = 1gives[1].nums = [4, -1, 4, -1, 7, 4, -1, 9],k = 2gives[4, -1]or[-1, 4]: both are correct.
