Arrays & Hashing

Bucket Sort by Frequency

Top K Frequent Elements

1Question

Top K Frequent Elements

MediumLeetCode 347 ↗

You are given an array of numbers nums and a number k. Return the k numbers that appear most often in the array.

Rules

The answer is always unique, so there are no ties at the cut-off. You may return the numbers in any order. We want the values, not how many times they appear.

Examples
Example 1
Input: [1,1,1,2,2,3], k = 2
Output: [1,2]

1 appears 3 times, 2 appears 2 times, 3 appears 1 time. The top 2 are 1 and 2.

Example 2
Input: [1], k = 1
Output: [1]

There is only one number, so it is the answer.

Example 3
Input: [1,2,1,2,1,2,3,1,3,2], k = 2
Output: [1,2]

1 appears 4 times, 2 appears 4 times, 3 appears 2 times. The top 2 are 1 and 2.

Constraints

1 ≤ nums.length ≤ 105

Up to 100,000 numbers. We must read every number at least once, so the best we can hope for is O(n).

−104 ≤ nums[i] ≤ 104

Values can be negative, so use a hash map to count, not a plain array indexed by value.

k is in the range [1, number of unique elements]

k is never bigger than the count of different numbers, so there are always enough numbers to return.

Follow-up

Your algorithm must be better than O(n log n). Sorting everything is too slow for this goal. Use buckets.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Bucket Sort by Frequency

Use the count itself as the index, so sorting is not needed.

When the thing you want to sort by is a small whole number (here: a count from 1 to n), you do not need a real sort. Put each item into the bucket with that number, then read the buckets in order:

buckets[count[num]].append(num) # then read from the last bucket to the first

Counting is O(n), filling the buckets is O(n), reading them is O(n). No step needs O(n log n).

How to spot this pattern

  • The question asks for the most or least frequent items.
  • You need a count per item, so a hash map is the first step.
  • The values you rank by are small whole numbers with a known maximum (a count is at most n).
  • The statement asks for something faster than O(n log n).

4Explanation

The big idea: Do the work in two small steps. First count, then group by count.

Step 1: Count

Walk through nums and build count[num], a map from each number to how many times it appears.

Step 2: Bucket and read

Put each number into buckets[count]. Then read the buckets from the biggest index down and stop after k numbers.

Why are n + 1 buckets enough? A number can appear at most n times, and at least once. So the counts are always between 1 and n. Index 0 is never used.

Why start from the end? The last bucket holds the numbers that appear most often. Reading from the end gives us the most frequent numbers first, so the first k numbers we meet are the answer.

5Brute Force

Count the numbers, then sort the different numbers by their count.

Idea

A direct way to say it: find how often each number appears, then rank them. So we:

  • Count every number in a hash map.
  • Sort the different numbers from the highest count to the lowest.
  • Return the first k numbers.
Python
def top_k_frequent_brute(nums, k):
    count = {}                                   # number -> how many times
    for num in nums:
        count[num] = count.get(num, 0) + 1

    # sort the different numbers, biggest count first
    ordered = sorted(count.keys(), key=lambda x: count[x], reverse=True)

    return ordered[:k]                           # the first k are the most frequent


print(top_k_frequent_brute([1, 1, 1, 2, 2, 3], 2))  # [1, 2]

6Optimal Solution

Count, then bucket the numbers by their count and read from the top.

Python
def top_k_frequent(nums, k):
    count = {}                                   # number -> how many times
    for num in nums:
        count[num] = count.get(num, 0) + 1

    buckets = [[] for _ in range(len(nums) + 1)] # index = count, value = numbers
    for num, freq in count.items():
        buckets[freq].append(num)

    result = []
    for freq in range(len(buckets) - 1, 0, -1):  # from the highest count down
        for num in buckets[freq]:
            result.append(num)
            if len(result) == k:                 # we have enough, stop
                return result

    return result


print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))  # [1, 2]

7Time and Space Complexity

Let n be the number of items in the array.

Brute force (count + sort)

Time: O(n log n)Space: O(n)

Optimal (bucket sort)

Time: O(n)Space: O(n)

How big is the difference?

Approximate number of steps (worst case, all numbers different):

nCount + sort (n × log₂ n)Bucket sort (n)
103310
1,0009,9661,000
100,000about 1.7 million100,000

For the biggest input in this problem, bucket sort does around 17 times less work. A heap (O(n log k)) lands in between.

8Visualization

Try:Use 1 to 15 whole numbers (from -99 to 99), separated by commas.
Current Number-
Its Count-
Picked-
1
1
1
2
2
3

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Count: count[num] += 1
Bucket: buckets[count[num]].append(num)
Read: from the highest count down, stop at k