Module 5 · Heaps · Applications of Heap

Top k frequent elements

Count each number with a HashMap, then keep the k most frequent in a min heap ordered by frequency: the root is the least frequent of the top k, replaced whenever something more frequent comes along.

frequencyMap counts each number. minHeap is a PriorityQueue of Elements ordered by frequency; each label reads number ×frequency.