Problem overview
The method topKFrequent receives a list of integers, nums, and an integer k. It 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, and the answer is guaranteed to be unique: every value in it appears more times than every value left out.
For nums = [1, 1, 1, 2, 2, 3] and k = 2 the answer is [1, 2]: 1 appears 3 times, 2 appears twice and 3 once. In [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 each appear 3 times and the others once, so [4, -1] and [-1, 4] are both correct. The lesson asks for O(n) time and O(n) extra space.
Approach: count, then bucket by frequency
The first half is the same for any solution: count how many times each value appears, with a dictionary that maps each value to its count. That is one pass over the list, since a dictionary finds a key in constant time on average.
The second half is choosing the k largest counts. Sorting the values by count costs O(n log n). A faster way uses one fact: a count can't be larger than len(nums). So make a list of buckets, one for each possible count, and put each value in the bucket for its count. This is a bucket sort: every value goes straight to its place, with no comparisons between counts.
The most frequent values then sit in the buckets with the highest indices. Start at the top bucket, len(nums), and walk down, collecting values until there are k of them. The walk visits at most len(nums) buckets, so the whole method stays O(n).
On [1, 1, 1, 2, 2, 3] the counts are {1: 3, 2: 2, 3: 1}. The list has 6 elements, so there are 7 buckets, and after filling them they are [[], [3], [2], [1], [], [], []]. Bucket 3 holds the value 1, bucket 2 holds 2 and bucket 1 holds 3. Walking down from bucket 6 collects 1 and then 2, and the method returns [1, 2].
Step by step
- Create an empty dictionary named
count. It maps each value to the number of times it appears. - Loop over every
numinnums. - Add one to its count:
count[num] = count.get(num, 0) + 1. Thegetwith a default of 0 handles a value seen for the first time. - Create the buckets with a list comprehension,
[[] for _ in range(len(nums) + 1)]. Counts run from 1 tolen(nums), so indexlen(nums)must exist, hence the+ 1.buckets[f]will hold the values that appear exactlyftimes. - Loop over
count.items(), unpacking each pair intonumandfreq. - Append
numtobuckets[freq]. - Create an empty
resultfor the answer. - Start
freqatlen(nums), the highest count a value can have. It is not known which buckets are full, so the walk starts at the top. - Loop while
len(result) < k. - Add the whole bucket to
resultwithextend. Because the answer is unique, a bucket never holds more values than are still needed. A bucket that pushedresultpastkwould mean a tie at the cut. - Move down to the next count:
freq -= 1. - Return
result.
The solution in Python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
result = []
freq = len(nums)
while len(result) < k:
result.extend(buckets[freq])
freq -= 1
return result
The Python details that matter here:
count.get(num, 0)returns 0 for a missing key. Writingcount[num] += 1for a new value raises aKeyError.- The list comprehension builds separate lists. It evaluates
[]once per item. The shortcut[[]] * nrepeats one list n times, so appending to one bucket would appear in all of them: appending 1 to the first of[[]] * 3gives[[1], [1], [1]]. _as a loop variable is a convention for a value that is not used.extendversusappend.extendadds each item of a list.appendwould add the whole bucket as one nested list.count.items()yields the key-value pairs, which theforloop unpacks directly.- Reusing
freq. The loop variable of the secondforand the later counter share a name. That is fine, because the first loop is finished by then andfreqis assigned afresh.
The standard library offers shorter ways, such as collections.Counter(nums).most_common(k), but that sorts by count and is O(n log n). The buckets are what keep this version linear.
Complexity
Time: O(n). Counting is one pass. Filling the buckets visits each distinct value once, and there are at most n of them. The walk down the buckets visits at most n + 1 of them, and the values it collects add up to k.
Space: O(n). The dictionary holds up to n distinct values, and the bucket list has n + 1 entries. Every value is stored in exactly one bucket.
Edge cases and common mistakes
- A single value.
[1]withk = 1gives[1]. There are 2 buckets, and the walk starts at bucket 1. kequals the number of distinct values.[1, 2, 3]withk = 3gives[1, 2, 3]. The walk empties every bucket down to count 1.- Negative values. They are ordinary dictionary keys. The buckets are indexed by count, never by the value, so a value like -1 causes no trouble.
- Ties below the cut. Values with equal counts share a bucket. The guarantee that the answer is unique means any tie is entirely inside the answer or entirely outside it, so the whole-bucket
extendnever overshootsk. - Bucket list too short. Using
len(nums)buckets instead oflen(nums) + 1fails when one value fills the list, because the countlen(nums)has no bucket. That raises anIndexError. - Wrong order is fine. The answer can come back in any order. For
[5, 5, 5, 2, 2, 3]withk = 1the answer is[5].
Testing
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[4, -1].nums = [5, 5, 5, 2, 2, 3],k = 1gives[5].nums = [1, 2, 3],k = 3gives[1, 2, 3].
