Find the k values that appear most often. Tally them in a map, then keep a k-spot leaderboard in a min-heap instead of sorting everything.
▼The problem
LeetCode 347 (Medium), Top K Frequent Elements. Given an integer array nums and an integer k, return the k most frequent elements (the answer is guaranteed to be unique; any order).
Example: nums = [7, 5, 9, 7, 9, 6, 8, 9, 8, 9, 8], k = 2 → [9, 8].
import heapq
def top_k_frequent(nums, k):
count = {}
for n in nums:
count[n] = count.get(n, 0) + 1
heap = []
for n, c in count.items():
heapq.heappush(heap, (c, n))
if len(heap) > k:
heapq.heappop(heap)
return [n for c, n in heap]TRY IT ON LEETCODE ▶The solution
import heapq
def top_k_frequent(nums, k):
count = {}
for n in nums:
count[n] = count.get(n, 0) + 1
heap = []
for n, c in count.items():
heapq.heappush(heap, (c, n))
if len(heap) > k:
heapq.heappop(heap)
return [n for c, n in heap]Transcript
Top K Frequent Elements. You get a list of numbers and a number k. Return the k values that appear most often, in any order.
Take seven, five, nine, seven, nine, six, eight, nine, eight, nine, eight, and k is two. Count them: nine appears four times, eight three times, seven twice, five and six once. So the answer is nine and eight.
The simple way: tally every value, sort them all by count, and keep the first k. That works, but the sort costs n log n, ordering values we'll never return. We only need the top k.
Instead, keep a leaderboard with exactly k spots. The entry that matters is the weakest one, since it's the next to go. So store the board as a min-heap: the smallest count sits on top, ready to check. Each newcomer joins. If that makes too many, pop the top, and the weakest is out.
Let's run it. Seven, with two, takes a spot. Five, with one, takes the other, and lands on top as the weakest. Nine arrives with four. That's three, so the top pops: five is out, and seven becomes the weakest. Six joins with one, but it's now the weakest, so it pops right back off. Eight's three knocks out seven. Nine and eight remain.
In code, a dictionary tallies each number. Then push each count and value onto the heap, count first, so it orders by count. Whenever the heap holds more than k, pop the smallest. The values left are the answer.
Counting takes one pass. The heap never holds more than k plus one, so each push and pop costs log k: n log k time, and O of n space for the counts. Bucketing values by count can even make it linear.
Count them, keep the best k, bump the weakest. That's Top K Frequent.