Top K Frequent Elements
Top K Frequent Elements is LeetCode 347 (Medium). Given an integer array nums and an integer k, return the k values that appear most often, in any order.
- The answer is guaranteed to be unique, so two values never tie for the last place.
numscan hold 10⁵ values, and the follow-up asks for better than O(n log n), so sorting every value by its count is not the target.
- 1 <= nums.length <= 10⁵
- -10⁴ <= nums[i] <= 10⁴
- k is in the range [1, the number of unique elements in the array]
- It is guaranteed that the answer is unique
Intuition
The problem is two jobs: count how often each value appears, then pick the k largest counts. Counting is one pass with a hash map.
Picking does not need a sort, because a count is a small whole number: no value can appear more than n times. So make n + 1 buckets and put each value into the bucket numbered by its count. Reading the buckets from n down to 1 meets the values from most to least frequent, and the first k values you meet are the answer.
Every step is a single pass, so the whole thing is O(n).
Use counting plus buckets when you need the most (or least) frequent items and every count is bounded by the input size; Sort Characters by Frequency (LeetCode 451) works the same way. When ties must be broken by another rule, as in Top K Frequent Words, a heap with a custom comparison is simpler.
Approach
Before reading on: in [1,1,1,2,2,3], what is the largest count any value could have? How could that limit let you order values by count without sorting them?
Two ways to solve it
Put each value in buckets[count], then read buckets from n down until k values are collected.
- Time: linear; no comparisons at all.
- Space:
n + 1lists, even when few values are distinct. - Follow-up: beats O(n log n) outright.
The fastest answer for this problem.
Push (count, value) pairs into a min-heap and pop whenever it holds more than k.
- Time: log k per distinct value.
- Space: the count map plus
kheap entries. - Reuse: works when counts are not bounded, or arrive as a stream.
The pattern most interviewers expect too.
Bucketing uses the fact that counts never exceed n, so it skips comparisons and runs in linear time. The steps, code and live demo below follow the bucket version; the heap code comes after the demo.
Count each value
Walk nums once and build count, a hash map from value to how many times it appears. From here on, the work is over the distinct values, which can be far fewer than n.
Put each value in the bucket for its count
Create n + 1 empty lists, buckets[0] to buckets[n]. For each value v with count c, append v to buckets[c]. The count is the index, so placing a value is O(1) and needs no comparison. Index n must exist, because one value can fill the whole array.
Read the buckets from the top
Loop c from n down to 1 and append every value in buckets[c] to the result. Stop as soon as the result holds k values. Higher buckets hold more frequent values, so the first k collected are the answer. The unique-answer guarantee means stopping halfway through a bucket never splits a tie.
Code in Python, C++ and Java
nums fills a hash map from value to how often it appears. 1 is new, so its count starts at 1.nums fills a hash map from value to how often it appears. 1 is new, so its count starts at 1.nums fills a hash map from value to how often it appears. 4 is new, so its count starts at 1.Min-heap of size k
Count the values, then push each (count, value) pair into a min-heap and pop the smallest whenever the heap grows past k. The k pairs left are the most frequent.
Common pitfalls
Making only n buckets
buckets = [[] for _ in range(len(nums))]
buckets = [[] for _ in range(len(nums) + 1)]
Counts run from 1 to n. With nums = [7, 7, 7], the count is 3 and buckets[3] must exist, so the list needs n + 1 slots.
Sorting every value by count
order = sorted(count, key=count.get, reverse=True) return order[:k]
# buckets: O(n), or a size-k heap: O(n log k)
It is correct, but sorting all distinct values costs O(n log n) when they are all different, which is exactly what the follow-up asks you to beat.
Putting the value first in heap pairs
heapq.heappush(heap, (num, c))
heapq.heappush(heap, (c, num))
Tuples compare by their first item. With the value first, the heap keeps the k largest numbers, not the k most frequent ones.
Edge cases
Every value is returned. The scan simply collects all of them before reaching k, so no special case is needed.
Complexity
Top K Frequent Elements vs Top K Frequent Words
The two problems are often confused, but ties change the tool.
| Top K Frequent Elements (347) | Top K Frequent Words (692) | |
|---|---|---|
| Ties | cannot happen at the cut (answer is unique) | broken alphabetically |
| Output order | any order | most frequent first, then alphabetical |
| Usual tool | buckets or a size-k min-heap | heap or sort with a two-part comparison |
Top K Frequent Elements FAQ
How do you solve this problem?
- Count: build a hash map from value to count.
- Bucket: put each value into
buckets[count], withn + 1buckets. - Collect: read buckets from
ndown to 1 until you havekvalues. - Complexity: O(n) time, O(n) space.
Is there a shorter Python solution?
Yes: return [v for v, _ in Counter(nums).most_common(k)]. With an argument, most_common(k) uses a heap internally, so it runs in O(n log k), the same as the heap version below.
Why a min-heap and not a max-heap?
A min-heap of size k keeps the weakest of the current top k on top, so one comparison decides whether a new value gets in. A max-heap of every distinct value also works (heapify, then pop k times), but it holds all values at once instead of only k.
Can quickselect solve it?
Yes. Partition the distinct values by count, as in Kth Largest Element, until the k most frequent sit on one side. It averages O(n) but can degrade to O(n²) on unlucky pivots, so buckets are the safer linear answer here.