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.
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;
}
}
O(N)
โ Iterating through the array.O(N log K)
โ Adding and removing elements from the heap.O(N log K)
.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].
K
greater than the number of unique elements.K
is large.