LeetCode #347 Medium

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.
  • nums can 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.
Constraints
  • 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
heaphash-tablebucket-sort
Open on LeetCode ↗
02

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).

How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def topKFrequent(self, nums: List[int], k: int) -> List[int]:
▶3 count = {}
▶4 for num in nums:
▶5 count[num] = count.get(num, 0) + 1
▶6 buckets = [[] for _ in range(len(nums) + 1)]
▶7 for num, c in count.items():
▶8 buckets[c].append(num)
▶9 res = []
▶10 for c in range(len(nums), 0, -1):
▶11 for num in buckets[c]:
▶12 res.append(num)
▶13 if len(res) == k:
▶14 return res
▶15 return res
nums111223count1× 1buckets by count123456result0 / 2empty1 seen 1 time
num1nums[0]
count[1]1
Phase 1: count. One pass over nums fills a hash map from value to how often it appears. 1 is new, so its count starts at 1.
nums111223count1× 2buckets by count123456result0 / 2empty1 seen 2 times
num1nums[1]
count[1]2
1 has been seen before, so its count goes up to 2.
nums111223count1× 3buckets by count123456result0 / 2empty1 seen 3 times
num1nums[2]
count[1]3
1 has been seen before, so its count goes up to 3.
nums111223count1× 32× 1buckets by count123456result0 / 2empty2 seen 1 time
num2nums[3]
count[2]1
2 is new, so its count starts at 1.
nums111223count1× 32× 2buckets by count123456result0 / 2empty2 seen 2 times
num2nums[4]
count[2]2
2 has been seen before, so its count goes up to 2.
nums111223count1× 32× 23× 1buckets by count123456result0 / 2empty3 seen 1 time
num3nums[5]
count[3]1
3 is new, so its count starts at 1.
nums111223count1× 32× 23× 1buckets by count1213456result0 / 2empty1 goes in bucket 3
value1
bucket3its count
Phase 2: bucket. A value can appear at most 6 times, so a list of 7 buckets can use the count itself as the index. 1 appears 3 times, so it goes into bucket 3. No sorting and no comparisons.
nums111223count1× 32× 23× 1buckets by count12213456result0 / 2empty2 goes in bucket 2
value2
bucket2its count
2 appears 2 times, so it goes into bucket 2. No sorting and no comparisons.
nums111223count1× 32× 23× 1buckets by count312213456result0 / 2empty3 goes in bucket 1
value3
bucket1its count
3 appears 1 time, so it goes into bucket 1. No sorting and no comparisons.
nums111223count1× 32× 23× 1buckets by count312213456result0 / 2emptybucket 6 is empty
bucket6no value appears 6 times
result0 of 2
Phase 3: collect. Walk the buckets from the highest count down, so the most frequent values come first. No value appears 6 times, so bucket 6 is empty. Move one bucket lower.
nums111223count1× 32× 23× 1buckets by count312213456result0 / 2emptybucket 5 is empty
bucket5no value appears 5 times
result0 of 2
No value appears 5 times, so bucket 5 is empty. Move one bucket lower.
nums111223count1× 32× 23× 1buckets by count312213456result0 / 2emptybucket 4 is empty
bucket4no value appears 4 times
result0 of 2
No value appears 4 times, so bucket 4 is empty. Move one bucket lower.
nums111223count1× 32× 23× 1buckets by count312213456result1 / 21take 1 from bucket 3
taken1appears 3 times
result[1]1 of 2
Take 1 from bucket 3: no value left unvisited appears more often. The result has 1 of 2, so keep going.
nums111223count1× 32× 23× 1buckets by count312213456result2 / 212result has 2 → return [1, 2]
taken2appears 2 times
result[1, 2]2 of 2
Take 2 from bucket 2: no value left unvisited appears more often. The result now holds 2 values, so return [1, 2] at once; lower buckets are never read. The problem promises the answer is unique, so no tie can cross this cut.
05

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.

▶1class Solution:
▶2 def topKFrequent(self, nums: List[int], k: int) -> List[int]:
▶3 count = Counter(nums)
▶4 heap = []
▶5 for num, c in count.items():
▶6 heapq.heappush(heap, (c, num))
▶7 if len(heap) > k:
▶8 heapq.heappop(heap)
▶9 return [num for _, num in heap]
06

Common pitfalls

Making only n buckets

✗ Wrong
buckets = [[] for _ in range(len(nums))]
✓ Right
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

✗ Wrong
order = sorted(count, key=count.get, reverse=True)
return order[:k]
✓ Right
# 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

✗ Wrong
heapq.heappush(heap, (num, c))
✓ Right
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.

07

Edge cases

k equals the number of distinct values

Every value is returned. The scan simply collects all of them before reaching k, so no special case is needed.

08

Complexity

Time
O(n)
Space
O(n)
Counting, bucketing and the scan each touch every value or bucket once. The map and the buckets hold O(n) entries.
09

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)
Tiescannot happen at the cut (answer is unique)broken alphabetically
Output orderany ordermost frequent first, then alphabetical
Usual toolbuckets or a size-k min-heapheap or sort with a two-part comparison
10

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], with n + 1 buckets.
  • Collect: read buckets from n down to 1 until you have k values.
  • 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.