Given an integer array nums and an integer k, return the
k most frequent elements. You may return the answer in any order.
nums=[1,1,1,2,2,3], k=2[1, 2]nums=[1,2,2,3,3,3], k=2[2, 3]nums=[4,4,4,6,6,1,1,1,1], k=2[1, 4]O(n)minH.offer(elem, freq)minH.size() > k: minH.poll() — evict least-frequent
We want the k largest frequencies. By keeping a min-heap
capped at size k, the root is always the weakest current candidate
(lowest frequency among our best k so far). When a new element arrives and makes the heap k+1, we
evict the root — guaranteed to be the least-valuable. After all unique keys are processed,
the heap holds exactly the answer. Runs in O(n log k) vs. O(n log n) for full sort.
You could count the frequencies, then sort all distinct values by frequency. That is O(n log n). With a heap of size k, we only keep the best k candidates.
First, count every value with a hash map. Then go through the map, and push each value into a min heap ordered by frequency. If the heap grows beyond k, poll the root, which is the least frequent value in it. At the end, the heap holds exactly the k most frequent values.
Count first, then keep the top k with a min heap. Bucket sort by frequency is the O(n) alternative.
Run the animation above on your own input, or watch the 1:47 video explanation of Top K Frequent Elements with a dry run and Java code.