Top K Frequent Elements in Java: Explanation & Practice
Find k most frequent elements
Problem summary
Given an array and integer k, return the k most frequent elements. Use HashMap + Heap or Bucket Sort.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
// Count frequencies with HashMap
// Use heap or bucket sort to get top k
// Print: 1 2
}
}Expected output and test cases
- [1,1,1,2,2,3], k=2 → 1,2
1 2
- [1], k=1 → 1
1
- [-1,-1,2,2,3], k=2
-1 2
Hints
- First, count frequency of each element with HashMap
- Use min-heap of size k to keep top k elements
- Or use bucket sort: bucket[frequency] = list of elements
- Iterate buckets from high to low frequency
Related Data Structures & Algorithms exercises
- Practice Kth Largest Element in Java
- Practice Merge K Sorted Lists in Java
- Practice Find Median from Data Stream in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler