Heaps and top-k
Use a priority queue to keep the smallest or largest items while data streams in.
22 min
A heap (priority queue) always gives you the smallest item quickly. Python's heapq module implements a min-heap on a plain list:
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappush(h, 3)
heapq.heappop(h) # 1: the smallest
h[0] # 3: peek at the smallest without removing it| Operation | Cost |
|---|---|
heappush | O(log n) |
heappop | O(log n) |
peek h[0] | O(1) |
heapify(list) | O(n) |
Python only has a min-heap. Push the negated value (-x) and negate again on the way out.
"The k largest", "the k most frequent", "the kth smallest". Sorting everything is O(n log n). A heap of size k does it in O(n log k), which matters when n is huge and k is small, or when data arrives as a stream you cannot store.
The k largest using a min-heap of size k: the heap holds the k biggest seen so far, and its smallest item (h[0]) is the threshold to beat.
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h) # drop the smallest of the k+1
# h now holds the k largestheapq.nlargest(k, nums) and heapq.nsmallest(k, nums) do this for you. In an interview, show you can build it by hand.
Heap entries can be tuples: Python compares the first item, then the second, and so on. To rank words by count (high first) and then alphabetically, push (-count, word): the most frequent comes out first, and ties come out A to Z.
Merging k sorted lists, scheduling the next task by priority, and finding a running median (a max-heap for the lower half and a min-heap for the upper).
Write top_k_frequent(words, k): the k most frequent words, most frequent first. Words with the same count come in alphabetical order. If there are fewer than k distinct words, return them all.
top_k_frequent(["b", "a", "b", "c", "a", "b"], 2) is ["b", "a"].
Your code must satisfy
- top_k_frequent(["b", "a", "b", "c", "a", "b"], 2)→["b","a"]example
- top_k_frequent(["x", "y", "z"], 2)→["x","y"]tie alphabetical
- top_k_frequent(["a", "a", "b"], 5)→["a","b"]k bigger than distinct
- top_k_frequent([], 3)→[]empty
- top_k_frequent(["a"], 0)→[]k zero
- top_k_frequent(["z", "z", "a"], 1)→["z"]count beats alphabet
import heapq
def top_k_frequent(words, k):
passWrite kth_largest(nums, k): the kth largest value in the list (so k = 1 is the maximum). Duplicates count separately. 1 <= k <= len(nums) always holds. Keep a min-heap of size k for O(n log k).
kth_largest([3, 2, 1, 5, 6, 4], 2) is 5.
Your code must satisfy
- kth_largest([3, 2, 1, 5, 6, 4], 2)→5example
- kth_largest([3, 2, 1], 1)→3maximum
- kth_largest([3, 2, 1], 3)→1minimum
- kth_largest([5, 5, 4], 2)→5duplicates
- kth_largest([8], 1)→8single
- kth_largest([-1, -5, -3], 2)→-3negatives
import heapq
def kth_largest(nums, k):
passThree ways to get the top k.
Sort everything
- Time
- O(n log n)
- Extra space
- O(n) or in place
- Streams?
- no, needs all data
Best for small n, simplest code
Min-heap of size k
- Time
- O(n log k)
- Extra space
- O(k)
- Streams?
- yes
Best for large n, small k, or a stream
`heapq.nlargest(k, nums)`
- Time
- O(n log k)
- Extra space
- O(k)
- Streams?
- needs an iterable
Best for real code: say you know it
“To get the k largest with a heap, I should use a max-heap.”
The words "largest" and "max" go together.
What is actually true
A min-heap of size k is better: its top is the smallest of the best k, which is exactly what you compare each new item against and throw away when beaten. A max-heap of everything costs O(n) memory.
How to catch yourself
Think of a bouncer holding k places: the weakest person inside is the one a newcomer must beat.
heapqis a min-heap on a list:heappush,heappop,h[0]in O(log n), O(log n) and O(1).- For a max-heap, push negated values; for ties, push tuples such as
(-count, word). - Top-k with a size-k min-heap is O(n log k) and works on streams.
- Name
heapq.nlargestin an interview, but be ready to build it.
Heap checks.
What does heapq.heappop return?
- AThe largest item
- BThe smallest item
- CThe newest item
- DA random item
How do you simulate a max-heap with heapq?
- AUse `heappop` twice
- BPush negated values
- CSort the list first
- DIt is not possible
Time to find the k largest of n items with a size-k heap?
- AO(n)
- BO(n log k)
- CO(n²)
- DO(k)
After pushing 5, 2, 8, 1 into a min-heap, what is h[0]?
Which tuple makes the most frequent word pop first, ties A to Z?
- A`(count, word)`
- B`(-count, word)`
- C`(word, count)`
- D`(-count, -word)`
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.