โ† Back to Index

๐Ÿ“š Top K Frequent Elements โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Top K Frequent Elements problem involves finding the K most frequent elements in an array. This is commonly solved using a min-heap or bucket sort depending on the constraints.

๐Ÿงฑ Pattern Template

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> frequencyMap = new HashMap<>();
        for (int num : nums) {
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }

        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(
            (a, b) -> a.getValue() - b.getValue()
        );

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

        // Step 2: Extract the top K frequent elements
        int[] result = new int[k];
        int index = 0;
        while (!minHeap.isEmpty()) {
            result[index++] = minHeap.poll().getKey();
        }

        return result;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Top K Frequent Elements

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Explanation:
- The frequency of 1 is 3, 2 is 2, and 3 is 1.
- The top 2 frequent elements are [1, 2].

๐Ÿ’ก Pro Tips