Top K Frequent Elements
Problem
Read an array and a number k. Print the k most frequent values. Sort them by frequency (highest first). If two values have the same frequency, the smaller value goes first.
Constraints
- 1 <= k <= number of different values
Examples
Input
6 1 1 1 2 2 3 2
Output
1 2
Solutions
Count the values with a map, then sort by count. For very large inputs a min-heap of size k (O(n log k)) or bucket sort (O(n)) is faster. This version is the simplest to read.
/*
* Problem : Process an array and a number k.
* Input : n, integers, then k.
* Output : The k most frequent values.
* Approach: Count, sort, take k.
* Time : O(n + d log d)
* Space : O(d)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a, int k) {
// Step 1: Count how often each value appears.
java.util.Map<Integer, Integer> counts = new java.util.HashMap<>();
for (int value : a) {
counts.merge(value, 1, Integer::sum);
}
// Step 2: Put the different values in a list and sort it. A higher count goes first. Equal counts: smaller value first.
java.util.List<Integer> values = new java.util.ArrayList<>(counts.keySet());
values.sort((x, y) -> {
int byCount = counts.get(y) - counts.get(x);
return byCount != 0 ? byCount : Integer.compare(x, y);
});
// Step 3: Take the first k values.
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = values.get(i);
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(Arrays.stream(solve(a, k)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- How do you sort by two keys?