Top K Frequent Elements solution explained
The Top K Frequent Elements solution has two steps: count how often each value appears with a hash map, then pick the k values with the highest counts. A min-heap of size k picks them in O(n log k), and bucketing values by their count picks them in O(n), since no count can exceed the length of the input.
By Evin JohnPublished 7 min read
Restating the problem
You get a list of integers and a number k. Some values appear many times, others once. Return the k values with the highest number of appearances. The values in your answer can be in any order unless the interviewer asks otherwise. Usually you may assume k is between one and the number of distinct values, and that the answer is unambiguous, meaning no tie straddles the cut-off between the k-th and the next value.
| Values | k | Answer | Counts behind it |
|---|---|---|---|
| [5, 3, 5, 8, 3, 5, 1] | 2 | [5, 3] | 5 appears three times, 3 twice, the rest once |
| [9] | 1 | [9] | Only one value exists |
| [4, 4, -2, -2, -2, 7] | 1 | [-2] | Negative values are counted like any other |
| [6, 2, 6, 2, 0] | 2 | [6, 2] | Both appear twice; 0 once |
Ask about ties at the boundary, whether the output must be sorted by frequency, how large n and the number of distinct values can be, and whether the data arrives all at once or as a stream. The tie question in particular changes what a correct answer even means.
What this problem reveals
Interviewers like this question because nearly everyone can count with a dictionary, and the interesting part is the selection step. It shows whether you know heaps well enough to keep one at a fixed size, and whether you notice the bound that makes bucket sort possible: a count can never be larger than n. Senior candidates are often pushed into the streaming version, where exact counts are too expensive.
Likely follow-ups
- Return the answer sorted from most to least frequent. Sort the k winners by count at the end, which costs O(k log k).
- Break ties alphabetically for words. Sort or heap on the pair (negative count, word) so equal counts fall back to text order.
- The input is a stream too large to store. Exact answers need a counter per distinct value. Approximate methods such as the Misra-Gries summary or a count-min sketch keep memory small at the cost of some error.
- The counts live across many machines. Count locally, merge partial counts by key, then select. This is the classic map-and-reduce shape.
- Get average O(n) without the bucket array. Quickselect on the distinct values by count partitions around a pivot, though its worst case is quadratic.
Baseline: count, then sort everything
Count each value, sort the distinct values by count from high to low, and take the first k. With u distinct values the sort is O(u log u), which is O(n log n) in the worst case when every value is distinct. It is clear, short and correct, so it is a good thing to say first. The question is whether you need to sort all u values when only k of them matter.
from collections import Counter
def top_k_by_sorting(values, k):
counts = Counter(values)
ranked = sorted(counts, key=lambda v: counts[v], reverse=True)
return ranked[:k]Better: a heap that never grows past k
Keep a min-heap of (count, value) pairs. Push each distinct value, and whenever the heap holds more than k entries, pop the smallest. The heap always contains the k strongest values seen so far, and its top is the weakest of them, the one to drop if something better arrives. Each push and pop costs O(log k), so the selection is O(u log k). When k is much smaller than the number of distinct values, this beats sorting.
import heapq
from collections import Counter
def top_k_heap(values, k):
counts = Counter(values)
keep = [] # min-heap of (count, value), never larger than k
for value, count in counts.items():
heapq.heappush(keep, (count, value))
if len(keep) > k:
heapq.heappop(keep)
return [value for count, value in keep]Python also offers heapq.nlargest(k, counts, key=counts.get), which does the same thing in one line. Use it if the interviewer is happy with library calls, and be ready to explain what it does inside.
Optimal: bucket by count
A value cannot appear more than n times. So build a list of n + 1 buckets where bucket c holds every value that appears exactly c times. Then walk the buckets from the highest count down, collecting values until you have k. Counting is O(n), filling the buckets is O(u), and the walk is O(n), so the total is linear. The price is an array as long as the input, even when most buckets stay empty.
from collections import Counter
def top_k_buckets(values, k):
counts = Counter(values)
by_count = [[] for _ in range(len(values) + 1)]
for value, count in counts.items():
by_count[count].append(value)
picked = []
for count in range(len(by_count) - 1, 0, -1):
for value in by_count[count]:
picked.append(value)
if len(picked) == k:
return picked
return pickedfunction topKBuckets(values, k) {
const counts = new Map();
for (const v of values) counts.set(v, (counts.get(v) || 0) + 1);
const byCount = Array.from({ length: values.length + 1 }, () => []);
for (const [value, count] of counts) byCount[count].push(value);
const picked = [];
for (let c = byCount.length - 1; c > 0 && picked.length < k; c--) {
for (const value of byCount[c]) {
picked.push(value);
if (picked.length === k) break;
}
}
return picked;
}Using a Map rather than a plain object for counting keeps the keys as numbers. With an object, keys become strings and negative or large values come back as text unless you convert them.
Comparing the options
| Selection step | Time | Extra space | Good when |
|---|---|---|---|
| Sort all distinct values by count | O(n + u log u) | O(u) | You want the simplest correct code |
| Min-heap of size k | O(n + u log k) | O(u + k) | k is small compared with u |
| Buckets by count | O(n) | O(n) | You want a strictly linear bound |
| Quickselect on counts | O(n) average, O(n + u²) worst | O(u) | Memory for buckets is a concern |
Edge cases
- k equal to the number of distinct values: return all of them.
- Every value distinct, so all counts are one and any k of them is acceptable unless ties are defined.
- A single value repeated n times.
- Negative numbers and zero as values.
- Ties at the k-th position, if the interviewer has not ruled them out. Say how your code chooses.
Typical mistakes
- Forgetting to pop when the heap passes k entries, so it grows to all u values and the selection quietly becomes O(u log u).
- Pushing (value, count) instead of (count, value), so the heap orders by value.
- Sizing the bucket array as n instead of n + 1, which breaks when one value fills the entire input.
- Sorting the raw input instead of the distinct values.
- Returning counts instead of the values.
Putting it into words
Fictional example
- Candidate
- Step one is always a frequency map, which is linear. The real question is how to pick the top k from it.
- Candidate
- Sorting all distinct values works. A min-heap capped at k is better when k is small, because each operation is log k. And since no count can exceed n, I can bucket values by count and walk down from the top, which is linear.
- Candidate
- I will write the bucket version, and I am assuming no tie at the cut-off. If ties need a rule, I would sort the last bucket by that rule.
Related walkthroughs
Counting with a dictionary is the same habit used in Two Sum. Heaps also solve the room-count follow-up in Merge Intervals. For a breadth-first walk that groups items by distance, much as buckets group values by count, see Binary Tree Level Order Traversal. The coding problems hub has the rest.
How Natively helps you practice
When you work through problems like this one, Natively can capture the prompt from a screenshot on Mac or Windows and suggest the counting step and which selection method fits the constraints. Because it also transcribes your practice interview, you can reread whether you justified the heap or bucket choice clearly. More on the AI interview assistant.
Questions people ask
What is the fastest solution to Top K Frequent Elements?
Bucket sort by count. Count each value, place values in buckets indexed by their count, then walk from the highest bucket down until you have k values. It runs in O(n) because no count can exceed n.
How does the heap solution work?
Keep a min-heap of (count, value) pairs and pop whenever it holds more than k entries. The heap ends with the k most frequent values in O(n + u log k) time, where u is the number of distinct values.
What if there are ties for the k-th place?
The usual version assumes there are none. If ties are possible, agree on a rule, such as smaller value first or alphabetical order for words, and apply it when selecting.
How do you find frequent items in a stream?
Exact counts need memory for every distinct value. Approximate summaries such as Misra-Gries or a count-min sketch keep memory small in exchange for some error.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
