mediumHeapHeap / Priority Queue

Top K Frequent Elements

mediumTime: O(n log k)Space: O(n)

Signals to notice

find k most frequent elementsfrequency counting then selectiondon't need full sort

Brute force first

Count frequencies, sort by frequency, take top k. Sorting is overkill when you only need the top k. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Count frequencies with a hash map, then use a min-heap of size k to track the top k elements. — the heap never grows beyond k elements. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

The min-heap's smallest element is always the threshold — if a new frequency is larger, swap it in. After processing all elements, the heap contains exactly the k most frequent. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Using a max-heap — that finds the maximum, not the top k. A min-heap of size k naturally evicts the smallest, keeping only the largest k frequencies. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Heap / Priority Queue Pattern