Video in progress
How do you find the k most frequent elements in an array?
First I count frequencies with a HashMap, then I keep the top ones in a min-heap (PriorityQueue) of size k. Time is O(n log k). It can also be done in O(n) with buckets by frequency.
📖 Answer
static List<Integer> topK(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.merge(x, 1, Integer::sum);
PriorityQueue<Map.Entry<Integer, Integer>> heap =
new PriorityQueue<>(Map.Entry.comparingByValue());
for (var e : freq.entrySet()) {
heap.offer(e);
if (heap.size() > k) heap.poll(); // we evict the smallest
}
List<Integer> res = new ArrayList<>();
for (var e : heap) res.add(e.getKey());
return res;
}
Why a min-heap and not a max-heap? We want the largest ones, but we keep only k in the heap. When a new element arrives, we need to kick out the weakest candidate quickly, and that one sits at the top of a min-heap. That way memory is O(k) and each operation is O(log k).
Sorting everything works too: O(m log m), where m is the number of distinct elements. On small data the difference isn't noticeable; when k is small and m is large (say the top 10 IPs out of millions of log lines), the heap clearly wins.
Note that a PriorityQueue iterator doesn't guarantee order. If you need the result in descending order, pull items out with poll() and reverse them.
Sign up to mark studied questions and save your progress.