49. Top K Frequent with a Heap
Difficulty: Medium · Topic: DSA for data engineers
Write top_k_frequent(items, k): the k most frequent items, most frequent first; equal counts are ordered by the item itself, ascending. Items are numbers or strings of one kind (comparable with each other).
Use a heap so the selection costs O(n log k) rather than sorting every distinct item.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
top_k_frequent([1, 1, 1, 2, 2, 3], 2)Expected: [1, 2]
Hints
Hint 1
Counter(items) gives the counts.Hint 2
heapq.nsmallest(k, counts.items(), key=...) keeps only k candidates at a time.Hint 3
The key(-count, item) ranks higher counts first and breaks ties by item.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
- Heaps, top-k and k-way merges · 7 min read. heapq, top-k in O(n log k), tie-breaking tuples, and merging sorted streams.
More Python problems
- Two Sum · Easy
- Valid Brackets · Easy
- First Non-Repeating Character · Easy
- Group Anagrams · Medium
- Longest Substring Without Repeats · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard