Top K Frequent Elements in Java: Explanation & Practice

Find the k most frequent elements

Problem summary

Given an array, find the k most frequently occurring elements.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        
        // Find top k frequent elements
        // Print space-separated
    }
}

Expected output and test cases

  • Top 2 frequent
    1 2
  • Top 1 frequent
    1
  • All elements
    1 2 3

Hints

  1. Count frequencies with HashMap
  2. Use PriorityQueue or bucket sort
  3. Return top k by frequency

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler