Skip to content

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 1Counter(items) gives the counts.
Hint 2heapq.nsmallest(k, counts.items(), key=...) keeps only k candidates at a time.
Hint 3The key (-count, item) ranks higher counts first and breaks ties by item.

Learn the concepts

More Python problems

All Python problems