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

  1. First, count frequency of each element with HashMap
  2. Use min-heap of size k to keep top k elements
  3. Or use bucket sort: bucket[frequency] = list of elements
  4. Iterate buckets from high to low frequency

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler