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
Process num=1 (appears 3 times in nums). Count map starts. Min-heap: [1 cnt=3]. Size 1 ≤ k=2. Keep.
1FUNCTION topKFrequent(nums, k):2 cnt = a lookup table (number → its 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 heap7 IF heap size > k: pop the least frequent (the min)8 END FOR9 RETURN the number from each entry left in the heap10END FUNCTION
← / → step · space play · Home restart