Problem overview
The method topKFrequent receives an array of integers, nums, and a number 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 value in it appears more often 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]. The statement asks for O(n) time and O(n) extra space, and notes that sorting the values by frequency would already cost O(n log n).
Approach: count, then bucket by count
Counting is the first half. One pass over nums with a dictionary from value to count takes O(n) time, because a dictionary finds a key in constant time on average.
The second half is choosing the k largest counts. Sorting the distinct values by count would take O(n log n) in the worst case. The way around it is that a count can't be larger than nums.count. So instead of comparing counts, the lesson uses each count as an index into an array of buckets: buckets[f] holds the values that appear exactly f times. This is a bucket sort, and it needs no comparisons.
For [1, 1, 1, 2, 2, 3] the counts are 1 appears 3 times, 2 appears 2 times and 3 appears once, and the buckets (indices 0 to 6) are:
[[], [3], [2], [1], [], [], []]
Bucket 3 holds the value 1, bucket 2 holds 2, and bucket 1 holds 3. Reading from the highest index down, 1 comes first, then 2. After two values, the answer is complete.
Step by step
- Create
countas avarof type[Int: Int], starting empty with[:]. It maps each value to the number of times it appears. - Loop over every
numinnums. - Add 1 to its count with
count[num, default: 0] += 1. Thedefaultis used when the key is missing, so a value seen for the first time starts from 0. - Create the buckets.
[[Int]](repeating: [], count: nums.count + 1)makes that many empty arrays. Counts range from 1 tonums.count, so indexnums.countmust exist, which is why there is a+ 1. - Loop over the dictionary taking each entry as
(num, freq). - Put each value in its bucket with
buckets[freq].append(num). - Create
result, an empty[Int]. - Start
freqatnums.count, the highest count a value could have, and read the buckets downward from there. Empty buckets add nothing. - Loop while
result.count < k. - Take a whole bucket with
append(contentsOf:), which adds every item of an array. The answer is unique, so a bucket never brings the result pastkvalues. - Move down with
freq -= 1. - Return
result.
The solution in Swift
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var count: [Int: Int] = [:]
for num in nums {
count[num, default: 0] += 1
}
var buckets = [[Int]](repeating: [], count: nums.count + 1)
for (num, freq) in count {
buckets[freq].append(num)
}
var result: [Int] = []
var freq = nums.count
while result.count < k {
result.append(contentsOf: buckets[freq])
freq -= 1
}
return result
}
}
Swift details worth knowing:
- Dictionary subscripts return optionals. A plain
count[num]has typeInt?, and it isnilfor a missing key. The formcount[num, default: 0]returns a plainInt, and it can be used with+=to update the entry in place. - Dictionary order is not fixed. Iterating
for (num, freq) in countvisits the entries in an order that Swift doesn't promise and that can change from one run of the program to the next. That only affects the order of values inside one bucket, and the problem allows any order. - Buckets are independent.
[[Int]](repeating: [], count: n)copies the same empty arrayntimes, but arrays are value types, so appending to one bucket doesn't touch the others. - Shadowing the name
freq. Thefreqinfor (num, freq) in countonly exists inside that loop. The latervar freqis a separate variable declared after it. appendagainstappend(contentsOf:).append(x)adds one element.append(contentsOf: xs)adds each element ofxs.
Complexity
Let n be the length of nums.
Time: O(n). Counting is one pass. Building the buckets creates n + 1 arrays and places each distinct value once. The final loop visits at most n buckets and appends each value at most once.
Space: O(n). The dictionary holds at most n entries and the buckets array has n + 1 slots, with every distinct value in exactly one of them.
Edge cases and common mistakes
- One value.
[1]withk = 1returns[1]. The only bucket used is bucket 1. - A value that fills the array.
[5, 5, 5, 5]withk = 1returns[5]. Its count is 4 =nums.count, which is why the buckets need the extra slot. - Negative values. They are fine as dictionary keys.
[4, -1, 4, -1, 7, 4, -1, 9]withk = 2returns 4 and -1, in either order. - Taking everything. With
[1, 1, 2, 2, 3, 3, 3]andk = 3, all three distinct values come back. The one with the highest count comes first, and the other two follow in whatever order their shared bucket holds them. - Ties at the cut. The method relies on the guarantee that there are none. For
[1, 2]andk = 1, both values have count 1 and share a bucket, so the method returns both,[2, 1]in one run, which is more thank. - A
kthat is too large. Asking for more values than there are distinct ones would makefreqgo below 0, and the bucket lookup would stop the program. The constraints rule it out. - Forgetting the
+ 1. Without it, a value that appearsnums.counttimes has no bucket, and appending to it is an index error.
Testing
[1, 1, 1, 2, 2, 3]withk = 2gives[1, 2].[1]withk = 1gives[1].[5, 5, 5, 5]withk = 1gives[5].[1, 2, 3, 3]withk = 1gives[3].[4, -1, 4, -1, 7, 4, -1, 9]withk = 2gives[4, -1]in one run, and the order may differ.
