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].
The solution
import heapq
def top_k_frequent(nums, k):
count = {}
for n in nums:
count[n] = count.get(n, 0) + 1 # tally
heap = [] # min-heap
for n, c in count.items():
heapq.heappush(heap, (c, n))
if len(heap) > k:
heapq.heappop(heap) # drop the weakest
return [n for c, n in heap]Transcript
Top K Frequent Elements. Given a list of numbers and a number k, return the k values that appear most often.
Take seven, five, nine, seven, nine, six, eight, nine, eight, nine, eight, and k is two. Nine appears four times and eight three times, so the answer is nine and eight.
The simple way: count every value, sort them all by count, and take the top k. That sort costs n log n, though we only need k winners.
Instead, keep a leaderboard with exactly k spots, stored as a min-heap. The weakest entry sits on top, cheap to check. Each newcomer joins, and if that makes too many, the weakest is kicked off.
In code, a hash map tallies every number. Then push each count and value onto the heap, and whenever it holds more than k, pop the smallest.
Let's run it. The tally: seven twice, five once, nine four times, six once, eight three times. Seven and five fill the board, and five is at risk. Nine arrives with four and bumps five out. Six has only one, so it bounces off. Eight's three knocks out seven. Nine and eight remain.
The heap never passes k plus one, so each push and pop costs log k: n log k time, and O of n space for the counts. Bucketing by count can even make it linear.
Count them, keep the best k, bump the weakest. That's Top K Frequent.