Example: Top K Frequent Elements - rFronteddu/general_wiki GitHub Wiki

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Solution

  • Create a map of frequencies
  • for each entry, add to a max heap
  • when heal size is > k, remove last element and continue
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // Step 1: Count the frequency of each element using a HashMap
        Map<Integer, Integer> frequencyMap = new HashMap<>();
        for (int num : nums) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }

        // Step 2: Use a PriorityQueue (min-heap) to keep track of k most frequent elements
        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>((a,b)-> 
            Integer.compare(a.getValue(), b.getValue());
        // alternative:
        // minHeap = new PriorityQueue<>(Comparator.comparing(Map.Entry::getValue));


        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) {
                // Remove the least frequent element in the heap
                minHeap.poll(); 
            }
        }

        // Step 3: Build the result list from the heap
        int[] result = new int[k];
        int i = 0;
        while (!minHeap.isEmpty()) {
            result[i] = minHeap.poll().getKey();
            i++;
        }

        return result;
    }
}
⚠️ **GitHub.com Fallback** ⚠️