Visualize

Pattern visualizer

Top K Frequent Elements

The insight: finding the top k by frequency doesn't require sorting every distinct value — you only need to track the k most frequent seen so far and be willing to evict the weakest one when a stronger candidate shows up. A min-heap capped at size k does this cheaply: its root is always the least frequent of the current k candidates, so any new element only has to beat that root to earn a spot, and popping the root when the heap overflows keeps exactly the k highest counts. That's O(n log k) instead of sorting all distinct counts. Animated on: Find the k most frequent elements from an array.

Min-heap of size k

time O(n log k)space O(k)step 1 / 7
1
[0]
1
[1]
1
[2]
2
[3]
2
[4]
3
[5]
line 2

Process num=1 (appears 3 times in nums). Count map starts. Min-heap: [1 cnt=3]. Size 1 ≤ k=2. Keep.

Pseudocode
1FUNCTION topKFrequent(nums, k):
2 cnt = a lookup table (numberits count)
3 FOR each n in nums: add one to cnt[n]
4 h = a min-heap keyed by count (least frequent on top)
5 FOR each (number n, count c) in cnt:
6 push (count c, number n) onto the heap
7 IF heap size > k: pop the least frequent (the min)
8 END FOR
9 RETURN the number from each entry left in the heap
10END FUNCTION

← / → step · space play · Home restart

Where to practice Heap