Top K Frequent Elements
Return the k values that appear most often in an array, by counting them and grouping them by count.
You are given an array of integers numskkk
Example 1
Output: [1, 2]
Explanation: 1 appears three times and 2 twice, more than 3, which appears once.
Example 2
Output: [1]
The Idea
You have probably seen a "most played" list in a music app, or a list of the most used words in a text. Both answer the same question: which items come up most often? This problem asks for the k
Look at Example 1, [1, 1, 1, 2, 2, 3]k = 2[1, 2]
The counting part is quick. The question is how to find the highest counts. Sorting the values by count works, but sorting is exactly what the problem asks us to beat. Is there a way to line the counts up without comparing them?
There is, because a count cannot be just any number. A value appears at least once and at most as many times as the array is long. Example 1 has six numbers, so every count is between 1 and 6. That means we can set up one bucket for each possible count and drop every value into the bucket of its count. Look at the picture below.
The top row shows the counts. In the row of buckets, value 1 sits in the bucket for count 3, value 2 in the bucket for count 2, and value 3 in the bucket for count 1. Bucket 0 stays empty, since every value appears at least once. Buckets 4, 5 and 6 stay empty too, because no value appears that often.
Now read the buckets from the right, starting at count 6. The first three are empty. Count 3 gives 1, count 2 gives 2, and with two values collected we stop. The result is [1, 2]
So the bucket positions themselves put the counts in order. Grouping items into buckets by a number like this is the idea behind bucket sort.
Solution Approach
Turning that idea into code means settling three things: how to count the values, how many buckets to make, and how to read the buckets.
Counting the values
Where do the counts live? A HashMap
How many buckets
How many buckets are needed? A value can appear at most n times, where n is the length of the array. That happens when every number in the array is the same value. So the buckets need positions 0 to n, which is n + 1 buckets. Position 0 stays empty, since every value in the map appears at least once, but it keeps each count equal to its bucket's position.
Each bucket is a list, because several values can share a count. In the picture, a fourth value appearing once would join 3 in the bucket for count 1.
Reading the buckets
In what order are the buckets read? From count n down to count 1, taking values until k
The simple way, sorting the distinct values by their count, takes O(n log n) time. The buckets do the same job in one pass over n + 1 positions.
Java Solution
The method topKFrequent
- First, count each value in a map,
. For every numbercount ,x stores 1 the first time and adds 1 after that. Example 1 gives 1 → 3, 2 → 2 and 3 → 1.count.merge(x, 1, Integer::sum) - Make the buckets: a list of lists,
, withbucket empty lists, one for each count from 0 to n.nums.length + 1 - Loop over the entries of
and add each value to the bucket at its count,count .bucket.get(e.getValue()) - Create the array
withresult places, andk , the number of places used so far. A loop movesfilled from n down to 1, and inside it a second loop copies the values of bucketf intof . Both loops stop adding onceresult reachesfilled .k - Return
.result
The maink
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class KFrequentElements {
public static int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) {
count.merge(x, 1, Integer::sum); // one more time for x
}
// bucket.get(f) holds the values that appear exactly f times (f is at most n)
List<List<Integer>> bucket = new ArrayList<>();
for (int i = 0; i <= nums.length; i++) {
bucket.add(new ArrayList<>());
}
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
bucket.get(e.getValue()).add(e.getKey());
}
int[] result = new int[k];
int filled = 0;
for (int f = nums.length; f >= 1 && filled < k; f--) { // most frequent first
for (int value : bucket.get(f)) {
if (filled < k) {
result[filled++] = value;
}
}
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(topKFrequent(new int[] {1, 1, 1, 2, 2, 3}, 2)));
System.out.println(Arrays.toString(topKFrequent(new int[] {1}, 1)));
System.out.println(Arrays.toString(topKFrequent(new int[] {7, 7, 7, 7}, 1)));
System.out.println(Arrays.toString(
topKFrequent(new int[] {4, 4, 6, 6, 6, -9, -9, -9, -9, 2}, 3)));
System.out.println(Arrays.toString(topKFrequent(new int[] {5, 3, 5, 1}, 3)));
}
}
Running it prints:
[1, 2]
[1]
[7]
[-9, 6, 4]
[5, 1, 3]
[1, 2][1][7][7, 7, 7, 7]nums.lengthIndexOutOfBoundsException
The fourth line, [-9, 6, 4]k = 3
The original implementation,
Complexity
The work is one pass to count, one pass to fill the buckets, and one pass to read them.
- Time: O(n), for an array of n numbers, because counting visits each number once, with a map update that takes one step on average. There are at most n distinct values to place, and reading walks the n + 1 buckets once.
- Space: O(n). The map holds at most n distinct values, the n + 1 buckets hold each of those values once, and
hasresult places.k
Using a number with a known limit directly as a position in an array is also the idea behind