Top K Frequent Elements (LeetCode 347): Solution and Explanation

Medium
Array
Hash Table
Divide And Conquer
Sorting
Heap
Bucket Sort
Counting
Quickselect

Given an integer array and a number k, return the k values that occur most often. The answer is guaranteed to be unique, and it can be returned in any order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Any solution starts by counting how often each value appears, which a hash map does in one pass. The interesting part is what comes next: picking the k values with the highest counts. The straightforward move is to sort the distinct values by count in descending order and take the first k. That is correct, but sorting costs O(d log d) for d distinct values, and the problem explicitly invites you to beat O(n log n).

A min heap of size k is the classic improvement. Push each (count, value) pair, and whenever the heap grows past k, pop the smallest. What remains are the top k, in O(d log k) time. That is already good, but there is a property of the counts that lets you skip comparisons entirely: a frequency can never be smaller than 1 or larger than n, the length of the array. Counts live in a small, bounded integer range.

When keys are bounded integers, bucket sort applies. Make an array of n + 1 buckets where bucket c holds every value that appears exactly c times. Filling the buckets is one pass over the count map. Then walk the buckets from the highest index down, collecting values until you have k of them. Every step is constant work, so the whole algorithm is linear. The trick is to index by frequency instead of by value, which inverts the usual counting map.

Approach: Bucket sort by frequency

  1. Create a dictionary count and a list freq of len(nums) + 1 empty lists, one bucket per possible frequency.
  2. Loop over nums and increment count[n] for each value.
  3. Loop over count.items() and append each value n to the bucket freq[c] for its count c.
  4. Walk i from len(freq) - 1 down to 1, scanning the buckets from highest frequency to lowest.
  5. Append each value in freq[i] to res, and return res as soon as its length reaches k.

Step-by-step example

nums = [1, 1, 1, 2, 2, 3], k = 2
  1. Counting gives count = {1: 3, 2: 2, 3: 1}.
  2. There are 7 buckets (indices 0 to 6). After filling: freq[1] = [3], freq[2] = [2], freq[3] = [1], and the rest are empty.
  3. Scan i = 6, 5 and 4: all empty.
  4. i = 3: append 1, so res = [1].
  5. i = 2: append 2, so res = [1, 2]. The length now equals k, so return [1, 2].

Code: Python, Java, C++

1class Solution:
2    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3        count = {}
4        freq = [[] for i in range(len(nums) + 1)]
5
6        for n in nums:
7            count[n] = 1 + count.get(n, 0)
8        for n, c in count.items():
9            freq[c].append(n)
10
11        res = []
12        for i in range(len(freq) - 1, 0, -1):
13            for n in freq[i]:
14                res.append(n)
15                if len(res) == k:
16                    return res

Time and space complexity

Time

O(n)

Counting is one pass over n elements, filling buckets is one pass over at most n distinct values, and the final scan visits at most n + 1 buckets and n values in total.

Space

O(n)

The count map holds up to n entries, and the bucket array has n + 1 lists that together contain each distinct value once.

Other approaches

Min heap of size k (time O(n log k), space O(n + k))

Count with a map, then push (count, value) pairs into a min heap and pop whenever it exceeds k. It uses only O(k) extra space beyond the counts and is a good choice when k is much smaller than the number of distinct values or when data arrives as a stream.

Quickselect on the counts (time O(n) average, space O(n))

Partition the distinct values around a pivot frequency until the top k are on one side. It runs in O(n) on average but degrades to O(n²) in the worst case and is harder to implement correctly.

Common mistakes

  • Allocating only len(nums) buckets. A value that fills the whole array has count n, so you need n + 1 slots to index freq[n].
  • Bucketing by value instead of by frequency. The point is that frequencies are bounded by n, while values can be as large as 10^4 or negative.
  • Checking len(res) == k only after finishing a bucket. A single bucket may hold more values than you need, so the check belongs inside the inner loop.
  • Creating the buckets with [[]] * (len(nums) + 1). That repeats one shared list object, so appending a value to any bucket appends it to all of them; the list comprehension in the reference code creates distinct lists.

Frequently asked questions

How do you find the top k frequent elements in O(n)?

Count occurrences with a hash map, then place each value into a bucket indexed by its count. Scanning the buckets from the highest count down yields the most frequent values in linear time.

Heap or bucket sort for top k frequent?

Bucket sort is O(n) and simplest when the whole array is available. A min heap of size k is O(n log k) but uses less memory for the selection and also works for streaming input.

Why are there n + 1 buckets?

A frequency can range from 1 to n, and Python lists are zero indexed, so you need indices 0 through n. Bucket 0 is simply never used.

What if two values tie for the k-th spot?

The problem guarantees a unique answer, so that tie cannot change the result. Without that guarantee, values in the same bucket would be returned in whatever order they were inserted.