Algorithms · Heaps

Top K Frequent Elements

Which k numbers show up the most?

The problem

Return the k numbers that appear most often in nums, most frequent first.

top_k([1, 1, 1, 2, 2, 3], 2)[1, 2]
top_k([1], 1)[1]
Heaps. Always know the biggest. A hospital waiting room: the most urgent patient is always seen next.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def top_k(nums, k):take the numbers and k
counts = []pairs of (how often, number)
for x in set(nums):for each different number
counts.append((nums.count(x), x))count it by scanning the whole list
counts.sort(reverse=True)most frequent first
return [x for _, x in counts[:k]]just the top k numbers

Now ask: what if there were a billion?

Counting billions of items exactly needs a lot of memory, so trending-topic systems use sketches: small structures that count approximately. Reddit counts views per post with a cousin of this idea, HyperLogLog.

Aim for O(n)🔥 boss

Think it through

What’s slow about calling nums.count(x) for every different number?

  • Nothing
  • Each call walks the whole list again
Show the answer

Each call walks the whole list again. Many counts × a whole walk each is the every-pair trap. Count everything in one pass with a dictionary.

No number can appear more than n times. How does that help you avoid sorting the counts?

  • It doesn’t
  • Make a bucket per count and read from the top
Show the answer

Make a bucket per count and read from the top. Counts are small whole numbers, so put each number in the bucket for its count, then read buckets from n downwards. Bucket sort: when values are bounded, you can beat sorting.

Stuck? 3 nudges, smallest first
  1. nums.count(x) scans the whole list. Doing that for every different number is the slow part.
  2. Count everything in one pass with a dictionary. Then you need the biggest counts, without a full sort if you can.
  3. No number appears more than len(nums) times, so make a bucket for each count and read the buckets from the top.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def top_k(nums, k):take the numbers and k
counts = {}number → how often
for x in nums:one pass to count everything
counts[x] = counts.get(x, 0) + 1one more of x
buckets = [[] for _ in range(len(nums) + 1)]bucket c holds numbers seen c times
for x, c in counts.items():drop each number in its bucket
buckets[c].append(x)no sorting needed
out = []the answer
for c in range(len(nums), 0, -1):walk the buckets, most frequent first
for x in buckets[c]:each number in this bucket
out.append(x)take it
if len(out) == k:got k?
return outdone
return out(fewer than k different numbers)

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with heaps