MemotivaLeetCode Patterns Flashcards: Heap and Priority Queue, Top K, Merge K Sorted

How do you find the top k frequent elements using a heap?

LeetCode Patterns Flashcards: Heap and Priority Queue, Top K, Merge K Sorted

Аудио-карточка · 0:30

Nortren·

How do you find the top k frequent elements using a heap?

0:30

First, build a frequency map counting occurrences of each element in O of n time. Then use a min-heap of size k: iterate through the frequency map, push each element with its count, and if the heap exceeds size k, remove the element with the lowest frequency. After processing all entries, the heap contains the k most frequent elements. This runs in O of m log k where m is the number of unique elements. An alternative O of n approach uses bucket sort: create an array of lists indexed by frequency, place elements into their frequency bucket, then collect from the highest buckets.
neetcode.io