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 nums and a number k. Return the k values that appear in the array most often, in any order. You can assume the answer is unique: there is never a tie for the last place in the top k. Try to do better than sorting, which takes O(n log n) time, where n is the length of the array.

Example 1
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Explanation: 1 appears three times and 2 twice, more than 3, which appears once.
Example 2
Input: nums = [1], k = 1
Output: [1]
Solution

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 items at the top of such a list.

Look at Example 1, [1, 1, 1, 2, 2, 3] with k = 2. Before anything can be compared, each value needs its count: 1 appears 3 times, 2 appears 2 times and 3 appears once. The two highest counts belong to 1 and 2, so the answer is [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.

Counts for [1, 1, 1, 2, 2, 3]: 1 appears 3 times, 2 twice, 3 once. Buckets for counts 0 to 6 hold 1 in bucket 3, 2 in bucket 2 and 3 in bucket 1. Reading from count 6 down collects 1 and 2, so the result is [1, 2].

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], and no count was ever compared with another.

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 from value to count fits well, because the values can be any integers, including negative ones and very large ones. One pass over the array adds 1 to the count of each number it meets, and each update takes a single step on average.

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 have been collected. Because the answer is unique, the last bucket read never holds more values than there are places left, so the order of values inside a bucket does not matter.

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 works in these steps:

  1. First, count each value in a map, count. For every number x, count.merge(x, 1, Integer::sum) stores 1 the first time and adds 1 after that. Example 1 gives 1 → 3, 2 → 2 and 3 → 1.
  2. Make the buckets: a list of lists, bucket, with nums.length + 1 empty lists, one for each count from 0 to n.
  3. Loop over the entries of count and add each value to the bucket at its count, bucket.get(e.getValue()).
  4. Create the array result with k places, and filled, the number of places used so far. A loop moves f from n down to 1, and inside it a second loop copies the values of bucket f into result. Both loops stop adding once filled reaches k.
  5. Return result.

The main method runs both examples, an array of one repeated value, an array with a negative value and four different counts, and a case where k takes every distinct value.

Java
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:

Output
[1, 2]
[1]
[7]
[-9, 6, 4]
[5, 1, 3]

[1, 2] and [1] match Examples 1 and 2. Look at the third line, [7]: in [7, 7, 7, 7] the value 7 appears 4 times, as often as the array is long, so it lands in the very last bucket, position 4. With only nums.length buckets, there would be no position 4. A version built that way throws IndexOutOfBoundsException on Example 2 already, where 1 appears once in an array of length 1.

The fourth line, [-9, 6, 4], comes out in order of count: -9 appears 4 times, 6 three times and 4 twice, while 2, with a single appearance, is left out. The negative value causes no trouble, because only counts are used as positions, never the values. In the last line, 1 and 3 both appear once and share a bucket. With k = 3 both are taken, and they come out in the order the map happened to list them.

The original implementation, TopKFrequentElements.java, is on GitHub.

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 result has k places.

Using a number with a known limit directly as a position in an array is also the idea behind Counting Sort.