PracticeNeetCode ↗LeetCode ↗
Given an integer array nums and an integer k, return the k most frequent elements. The answer can be in any order.
buckets, an array of length n+1, where buckets[f] holds every number with frequency f.buckets[count[num]].k elements.Time: O(n) — Space: O(n)
def topKFrequent(nums: list[int], k: int) -> list[int]:
count = {}
for n in nums:
count[n] = count.get(n, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for n, freq in count.items():
buckets[freq].append(n)
result = []
for freq in range(len(buckets) - 1, 0, -1):
for n in buckets[freq]:
result.append(n)
if len(result) == k:
return result
return resultHow the solution above works, piece by piece.
buckets = [[] for _ in range(len(nums) + 1)]: index = frequency. No number can appear more than len(nums) times, so this is always big enough.buckets[freq].append(n): file each number under its count. This replaces sorting by frequency, which would cost O(n log n).freq from high to low and collect numbers until k are gathered, then return.Running it on nums = [1, 1, 1, 2, 2, 3], k = 2:
NeetCode — Top K Frequent Elements, Bucket Sort, LeetCode 347