int nums[] = {1,1,1,2,2,3}; int k = 2; // Frequency map: {1:3, 2:2, 3:1} // Using a min-heap to keep top k frequent elements // Final output is the elements in the heap // Output order does not matter // Result: [1, 2]
The frequencies are 1:3, 2:2, 3:1. The top 2 frequent elements are 1 and 2. The min-heap keeps the smallest frequency on top, so 3 is removed first.
Using a min-heap of size k lets us keep the k most frequent elements by removing the smallest frequency when adding a new element.
Without heapify after push, the heap structure breaks, so the smallest frequency may not be at the top, causing wrong results.
Both 5 and 6 have frequency 2, but 5 is smaller, so the heap keeps 5 and 6 as top 2.
Push frequency 2 for element 2, then frequency 3 for element 3, then frequency 1 for element 5. After pushing all, pop the smallest frequency (1,5) to keep size 2.
