Top K Frequent Elements
Find the k most frequent values
DSA, Medium, Arrays & Hashing
Which structure or algorithm, and what does it cost.
A list nums holds whole numbers, and k is a whole number. Return the k values with the highest counts in nums. Ties never matter: the value in place k always has a higher count than the next one, or there is no next one. The order of the values you return is free.
Examples
Constraints
- 1 <= length of
nums<= 100,000. - Each number is a whole number between -100,000 and 100,000.
- 1 <=
k<= the number of different values innums.
Your answer must contain
- The simple method and why it is too slow; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for better than O(n log n) time. O(n) is possible.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
You need two things for each value: how many times it appears, and then which values have the biggest counts.
Hint 2 the approach
Counts are whole numbers from 1 up to the length of the list. Think of a row of boxes, one box for each possible count.
Hint 3 the key step
Count each value in a dictionary. Put each value in the box for its count. Read the boxes from the largest count down, and stop when you have k values.
Walkthrough
Full walkthrough brute force to best
Brute force
For each different value, scan the whole list to count it. Then sort the values by count and take the first k. The scans cost O(n) for each of up to n different values, so O(n^2) time. For 100,000 numbers that is about 10 billion steps.
Better method
Count every value in one pass with a dictionary. Then sort the different values by count, largest first, and take the first k. That is O(n) to count and O(n log n) to sort.
Keep a min-heap of size k over the pairs of count and value. Push each pair, and drop the smallest when the heap grows past k. That is O(n log k) time and O(n) memory, which beats the full sort when k is small.
Best method
A count can only be a whole number from 1 to n, where n is the length of the list. So use a list of n + 1 boxes, and put each value in the box for its count. The box at position c holds the values that appear c times. Read the boxes from n down to 1 and collect values until you have k of them. This is right because the boxes are in count order, so the first k values you meet have the largest counts. The guarantee about ties means the box where you stop never splits a tie. No sort is needed, so the work is linear.
Hand trace
Run on [5, 5, 5, 2, 2, 9, 7, 7, 7, 7] with k = 2. Counting gives 5 with 3, 2 with 2, 9 with 1 and 7 with 4. The list has 10 numbers, so there are 11 boxes. Box 3 holds 5, box 2 holds 2, box 1 holds 9 and box 4 holds 7. Read from box 10 down. Boxes 10 to 5 are empty. Box 4 gives 7, so the answer is [7]. Box 3 gives 5, so the answer is [7, 5] and it holds k = 2 values. Return [7, 5].
Code
def top_k(nums, k):
counts = {}
for x in nums:
counts[x] = counts.get(x, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for x, c in counts.items():
buckets[c].append(x)
answer = []
for c in range(len(nums), 0, -1):
for x in buckets[c]:
answer.append(x)
if len(answer) == k:
return answer
return answerTime and memory
O(n) time, because counting is one pass, filling the boxes visits each different value once, and reading the boxes visits at most n + 1 boxes and n values. O(n) memory for the dictionary and the boxes.
Common mistakes
- Sorting the values and not the counts. The largest values are not the most frequent ones.
- Making the boxes as long as the biggest value instead of the list length. Values can be negative and large, but a count never passes n.
- Returning the counts instead of the values. The question asks which values are frequent.
- Pushing every pair into a heap of unlimited size. The heap should hold only k pairs, or it costs as much as a full sort.