Four interview problems that keep the best few of many items. The move: put every tie rule and filter into the key, then keep a heap of size k with the worst kept item on top.
You work on a payments app, a ride app, a social app and a parcel app. Each one has a long stream of items and asks for the best few. Sorting everything to read the first k is the first idea, and it is correct. It costs too much when the stream is long or the question comes again and again.
Here is what each problem ranks, and the twist that makes it a problem of its own.
| Problem | What is ranked | The twist |
|---|---|---|
| Kth largest in a stream | different amounts | a repeated amount counts once |
| Top k frequent elements | places, by how often each is used | one answer for each zone, ties to the smaller place |
| K most frequent words | words, by their uses | a word needs enough different posts, ties alphabetical |
| K closest depots to the origin | open depots, by distance | depots open and close between asks |
The heap is the same in all four. The ranking, and what happens to ties, is not.
Exercise · Predict the output: What does the heap of size 3 keep?. The heap keeps the three largest values so far, with the smallest of the three on top. A new value enters only if it is larger than the top. What does the code print?
import heapq
values = [4, 9, 2, 7, 7, 5, 10]
k = 3
heap = []
replaced = 0
for v in values:
if len(heap) < k:
heapq.heappush(heap, v)
elif v > heap[0]:
heapq.heapreplace(heap, v)
replaced += 1
print(heap[0], replaced)The move has two steps, and you take both before you write code.
First, write the key: the one value, or one tuple, whose order is the ranking. A count is not enough when ties matter. For the trending words the key is the uses, then the word in reverse alphabetical order, so the worst item always has the smallest key.
Second, decide where the filters go. A filter that depends on a total, such as the number of different posts of a word, runs while you count. The heap sees only the items that passed.
After each item, the heap holds the best k items so far and the worst of them is on top. A new item enters only if its key beats that top, and it then replaces it.
The cost is the reason to use it. With n items, a heap of size k does at most n pushes and n replacements, and each costs about log k steps. Sorting costs about log n steps for every item, and it needs all n items in memory at once.
A heap of size k holds the best k, with the worst on top. A new value must beat the top to enter.
Exercise · Find the bug: One place too many. This returns the kth largest value after each new value, or -1 until k values have arrived. It is right for some inputs and wrong for others. Which line is wrong?
import heapq
def kth_after_each(k, values):
heap = []
answers = []
for v in values:
if len(heap) <= k:
heapq.heappush(heap, v)
elif v > heap[0]:
heapq.heapreplace(heap, v)
answers.append(heap[0] if len(heap) >= k else -1)
return answersThe Academy lesson Heaps and priority queues keeps the best k of a stream, and Top k and k-way merge adds a tie rule and a stop-early search. This street does not teach them again. It changes four things.
Repeats count once. A heap does not know that 50 is already held. Keep a set of the held values beside it, and remove a value from the set when the heap evicts it.
Take the amounts 50, 30, 50, 40 and 30 with k = 3. The plain heap reports a threshold after the third payment. The right answer is still -1, because only two different amounts have arrived.
The ranking is a count. Count first, then rank. When the answer is one row for each group, sort the events so equal ones sit together, count each run, and keep a small heap for each group. The heap is emptied when the group changes.
A filter comes before the heap. In the trending words, a word used 6 times in one post is not eligible. Count its uses and the number of different posts together, drop it, and only then push.
Items can leave. Close a depot and the heap of size k is wrong. With depots at distances 1, 4 and 9, and k = 2, the heap keeps depots 1 and 4. Close depot 1, and the answer should be depots 4 and 9, but depot 9 was discarded long ago.
The fix is to keep every opened depot in the heap. At each ask, pop up to k open depots, drop the closed ones for good, and push the open ones back.
That last idea is the start of lazy deletion, which the street Custom heaps and lazy deletion works out.
A plain heap fills its places with equal amounts. Keep a set of held values and skip a value already in it.
Exercise · Break it: The amount that repeats. This returns the kth largest different amount after each payment, or -1 until k different amounts have arrived. It keeps a heap of size k. Find an input where it gives a wrong answer.
import heapq
def kth_distinct(k, amounts):
heap = []
answers = []
for amount in amounts:
if len(heap) < k:
heapq.heappush(heap, amount)
elif amount > heap[0]:
heapq.heapreplace(heap, amount)
answers.append(heap[0] if len(heap) == k else -1)
return answersSolve them in this order. The first is the plain bounded heap with one extra rule. The next two rank by a count, and the last one lets items leave.
Before you code each problem, write three lines: the key, what the heap holds, and what the twist adds. If you cannot name the key, read the ranking sentence of the statement again.
Give each problem about 25 minutes. Spend the first five on the three lines, and say them out loud as you would to an interviewer. Then test the edge cases before you submit.
Four cases come back on every rung. They are k larger than the number of items, k equal to 1, a tie at the boundary, and one value repeated many times. Write one small test for each.
When a solution fails, check the tie rule first. Most wrong answers on this street come from a key that cannot tell two items apart, so the heap picks one by accident.
Checkpoint · Top k patterns
Q1/5 You keep the 5 largest values of a stream in a heap. Which item sits on top, and when does a new value enter?
Answer: B
The top is the worst kept item, so it is the one to beat. A larger value replaces it, and the heap never holds more than k values.
Q2/5 Trending words must break ties alphabetically. Where does that rule belong?
Answer: B
If the key cannot tell two words apart, the heap keeps one of them by accident. A tie rule in the key makes the choice the same on every run.
Q3/5 The amounts 5, 5 arrive with k = 2, and a repeated amount counts once. What is the threshold after the second payment?
Answer: B
The plain heap would hold 5 and 5 and report 5. With a set of held values the second 5 is skipped, so the heap holds one amount and there is no threshold yet.
Q4/5 A word is used 6 times, but all in one post, and the rule asks for at least 2 different posts. When do you apply the rule?
Answer: B
A filter that depends on a total is evaluated when the totals are complete. The heap then ranks only the items that passed.
Q5/5 Depots can close between asks. Why does a heap of size k give wrong answers?
Answer: B
With depots at distances 1, 4 and 9 and k = 2, closing the nearest depot makes the third one part of the answer. Keep every open depot and take k valid ones at each ask.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.