Start learning free

LESSON 85 OF 321 · HASH TABLE

Top K Frequent Elements in Java: Counting and Bucket Sort in O(n)

Practice O(n) Read the full explanation

You get an array of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 14
    Ctrl + Enter to check

    JAVA · HASH TABLE

    Top K Frequent Elements in Java, explained

    Problem overview

    The method topKFrequent receives an int[] nums and an integer k, and returns an int[] with the k values that appear most often in nums, in any order. The frequency of a value is how many times it appears. The answer is guaranteed to be unique: every value in it appears more times than every value left out.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears 3 times, 2 appears twice and 3 once, so the answer is [1, 2]. For [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 appear 3 times each and 7 and 9 once, so the answer is [-1, 4] or [4, -1].

    Approach: count, then bucket by count

    The first half is the same in every solution: count each value in a hash map, in one pass. After that, the straightforward move is to sort the distinct values by count and take the first k. That costs O(n log n), and the lesson wants O(n).

    The way around it is to notice that a count is a whole number between 1 and nums.length. So instead of comparing counts, give every possible count its own bucket, a list of the values that appear exactly that many times, and drop each value straight into the bucket for its count. That is a bucket sort. Then read the buckets from the highest count down, collecting values until you have k of them.

    For [1, 1, 1, 2, 2, 3] the counts are {1=3, 2=2, 3=1}. With 6 elements there are buckets 0 to 6, and the filled ones are bucket 1 holding 3, bucket 2 holding 2 and bucket 3 holding 1. Reading from bucket 6 down, the first non-empty bucket is 3, which gives 1, and the next is 2, which gives 2. With k = 2 the answer is [1, 2].

    In Java terms, after the values are distributed, the buckets list is [[], [3], [2], [1], [], [], []].

    Step by step

    1. Create the map. Map<Integer, Integer> count = new HashMap<>() maps each value to the number of times it appears.
    2. Loop over nums with a for-each loop, for (int num : nums).
    3. Add one to the value's count with count.put(num, count.getOrDefault(num, 0) + 1). For a value seen for the first time, getOrDefault gives 0, where get would give null.
    4. Create buckets as a List<List<Integer>>. buckets.get(f) will hold the values that appear exactly f times.
    5. Fill it with empty lists. Loop i from 0 while i <= nums.length and add(new ArrayList<>()) each time. Counts run from 1 to nums.length, so indices 0 to nums.length need nums.length + 1 buckets. Each bucket needs its own list, so every pass creates a new one.
    6. Distribute the values. For each key num in count.keySet(), add it to the bucket at index count.get(num).
    7. Prepare the answer. Create result, a List<Integer>, and an int freq starting at nums.length, the highest possible count.
    8. Collect from the top. While result.size() < k, call result.addAll(buckets.get(freq)) and then freq--. Empty buckets add nothing. The loop visits at most nums.length buckets, so it stays O(n).
    9. Convert to an array. result.stream().mapToInt(i -> i).toArray() turns the list of Integer into an int[].

    The solution in Java

    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            Map<Integer, Integer> count = new HashMap<>();
            for (int num : nums) {
                count.put(num, count.getOrDefault(num, 0) + 1);
            }
            List<List<Integer>> buckets = new ArrayList<>();
            for (int i = 0; i <= nums.length; i++) {
                buckets.add(new ArrayList<>());
            }
            for (int num : count.keySet()) {
                buckets.get(count.get(num)).add(num);
            }
            List<Integer> result = new ArrayList<>();
            int freq = nums.length;
            while (result.size() < k) {
                result.addAll(buckets.get(freq));
                freq--;
            }
            return result.stream().mapToInt(i -> i).toArray();
        }
    }
    

    The Java details worth a closer look:

    • HashMap.get returns null for a missing key. Unboxing that null into an int throws NullPointerException. getOrDefault(num, 0) avoids it. Here count.get(num) is safe because num comes from count.keySet().
    • Boxing and unboxing. Generic collections hold Integer objects, not int. The compiler converts automatically in for (int num : count.keySet()) and in buckets.get(count.get(num)), where an Integer becomes the int index.
    • Why addAll. add(list) would put the whole bucket into result as one element, which does not compile for a List<Integer>. addAll adds each element.
    • new ArrayList<>() in a loop. Adding the same list object nums.length + 1 times would make every bucket the same bucket. The loop body creates a new list per pass.
    • The stream conversion. mapToInt(i -> i) unboxes each Integer to an int, and toArray() then builds an int[]. A plain result.toArray() would give an Object[], which is not what the method returns.
    • Order of the answer. A HashMap does not promise an iteration order, so values in the same bucket can come out in either order. The statement accepts any order. On the second example the code returns [-1, 4].

    Complexity

    Time: O(n). Counting is one pass over nums. Building the buckets takes nums.length + 1 steps. Distributing the values takes one step per distinct value, and there are at most n of them. Collecting visits at most nums.length buckets and adds each value at most once.

    Space: O(n). The map holds at most n entries, there are nums.length + 1 buckets, and the buckets together hold each distinct value once.

    Edge cases and common mistakes

    • One element. [1] with k = 1 gives [1]. There are two buckets, and bucket 1 holds the value.
    • One distinct value. [5, 5, 5, 5] with k = 1 gives [5]. It sits in bucket 4, which is the first one read.
    • Negative values. Values are map keys, never indices, so negatives like -1 need no special care. Only the counts index the buckets.
    • Too few buckets. Creating nums.length buckets instead of nums.length + 1 breaks when a single value fills the array: its count equals nums.length, and that index would not exist.
    • Ties at the cut. The statement guarantees none. If the guarantee did not hold, for example k = 3 on the second example, where three values are needed but two share the last place, a whole bucket would be added and the result would have 4 values: [-1, 4, 7, 9]. This lesson's tests never ask for such a case.
    • Sorting by count instead. It works, but it is O(n log n). The bucket idea works because a count has a small, known range.

    Testing

    • nums = [1, 1, 1, 2, 2, 3], k = 2 gives [1, 2].
    • nums = [1], k = 1 gives [1].
    • nums = [4, -1, 4, -1, 7, 4, -1, 9], k = 2 gives [-1, 4], which is the same set as [4, -1].
    • nums = [5, 5, 5, 5], k = 1 gives [5].
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free