Coding interview problems โบ Heaps & Top-K
๐บ Heaps & Top-K Medium
Top K Frequent Elements
Top K Frequent Elements: count with a hash map, then keep a size-k min-heap of frequencies or bucket by count for O(n). Tested Python and a live visual.
Also searched as: k most frequent elements ยท top k frequent using heap ยท bucket sort frequency
Try it live Free
Binary Heap & Priority Queue
Push and pop in the heap lab to see why the smallest entry is always on top; here the heap is ordered by frequency, so the least frequent candidate is the one that gets evicted.
Also useful: Hash Tables
The problem
Given a list of integers and an integer k, return the k values that appear most often, in any order. You may assume the answer is unique, meaning there is no tie at the k-th place.
The key insight
This is two small problems. First, count every value with a hash map in one pass. Then pick the k largest counts: a min-heap of size k does that in O(m log k) for m distinct values, because whenever the heap grows past k you throw away the least frequent value so far.
Step-by-step approach
- Count frequencies with
collections.Counter(nums). - For each
(value, count), push(count, value)onto a min-heap. - Whenever the heap holds more than
kentries, pop the smallest count. - The heap now holds the k most frequent values; return them.
Python solution
import heapq
from collections import Counter
def top_k_frequent(nums, k):
counts = Counter(nums) # value -> frequency
heap = [] # min-heap of (count, value)
for value, c in counts.items():
heapq.heappush(heap, (c, value))
if len(heap) > k:
heapq.heappop(heap) # drop the least frequent
return [value for c, value in heap]Complexity
Counting is O(n) for n numbers. Each of the m distinct values is pushed once onto a heap that never exceeds k + 1 entries, costing O(log k) each.
Common mistakes
- Pushing
(value, count)instead of(count, value), so the heap orders by value rather than frequency. - Using a max-heap of all distinct values and popping k times; correct, but O(m + k log m) and easy to get backwards.
- Returning the counts instead of the values.
Frequently asked questions
What is the time and space complexity of Top K Frequent Elements?
With a size-k heap it is O(n + m log k) time for n numbers and m distinct values, and O(m + k) space for the counter and the heap.
How does the O(n) bucket sort solution work?
Make n + 1 buckets where bucket c lists the values that appear exactly c times. Walk the buckets from high to low frequency, collecting values until you have k. It runs in O(n) time and space.
Can I just use Counter.most_common(k)?
Yes, it returns the k most frequent pairs and uses a heap internally for small k. It is a good shortcut in an online test; in an interview, be ready to explain or write the heap version.
What changes if ties are possible?
You need a tie-break rule, for example smaller value first. Encode it in the heap key, such as (count, -value), so the heap evicts the right element.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Heaps & Top-K Binary Heap & Priority Queue lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.