Three harder merge problems on sorted lists, after the Academy lesson. The move: decide what each pop must do, then push the next item of the same list, so the heap never holds more than k.
You work on a monitoring tool, a search page and a bus timetable. Each has many lists that are already sorted: event times for each service, document numbers for each query word, departure times for each line. The Academy lesson Top k and k-way merge merges such lists with a heap of fronts.
This street shares that name, and it does not teach the merge again. It adds three harder variants. In each one the merge is a means, not the answer.
| Problem | What one pop does | What the answer is |
|---|---|---|
| Merge sorted event streams | records which stream the event came from | the list of stream numbers in time order |
| Merge k sorted lists | pops every entry with the same document | the documents found in at least a given number of lists |
| Smallest range across k lists | moves the right end of a window | the shortest window that touches enough lists |
Read the middle column first. It tells you what the loop around the heap must do, and the rest follows.
Exercise · Predict the output: Which stream comes first?. Each entry is a time, then the stream number, then the position in the stream. The heap compares them in that order. What does the code print?
import heapq
streams = [[2, 5], [1, 2, 6], [2]]
heap = [(s[0], i, 0) for i, s in enumerate(streams)]
heapq.heapify(heap)
order = []
while heap:
t, i, j = heapq.heappop(heap)
order.append(i)
if j + 1 < len(streams[i]):
heapq.heappush(heap, (streams[i][j + 1], i, j + 1))
print(*order)Before you write code, finish one sentence: "When I pop the smallest item, I ..." The sentence is different on every rung of this street.
For the event streams it is "record the stream number". For the documents it is "keep popping while the top holds the same document, and count". For the range it is "add the item to the window and, if the window covers enough lists, shrink it".
What does not change is what you push. Every pop is followed by a push of the next item of the same list, when it has one.
The heap holds the first unread item of every list that still has items, so the top is the smallest unread item overall. After each pop, push the next item of the same list.
That rule bounds the heap at k entries, however long the lists are. It also explains the cost. With 1,000 lists of 100 items each, merging the lists one after another into a growing result moves 50,050,000 items. The heap makes 100,000 pops, with 1,095,226 comparisons in total.
After each pop, push the next item of the same list. The heap then holds one front for each list.
Exercise · Find the bug: The last event is missing. This merges the streams and returns the stream number of each event, in time order. Some events never appear in the answer. Which line is wrong?
import heapq
def merged_sources(streams):
heap = [(s[0], i, 0) for i, s in enumerate(streams) if s]
heapq.heapify(heap)
order = []
while heap:
t, i, j = heapq.heappop(heap)
order.append(i)
if j + 2 < len(streams[i]):
heapq.heappush(heap, (streams[i][j + 1], i, j + 1))
return orderThe Academy lesson Top k and k-way merge merged lists into one output list, using the heap from Heaps and priority queues. This street changes three things.
The tie rule is part of the entry. Equal times are common in logs. Put the list number after the time, as in the prediction above, and the heap breaks every tie the same way. Without it, equal entries leave the heap in an order you did not choose.
An empty list needs a guard. Push the first item of a list only when the list has one. With streams [3], [] and [1, 3], the answer is [2, 0, 2].
The merge is not the answer. To find documents that appear in at least need lists, you never build the merged list. Pop the smallest document, then keep popping while the top is the same document. The number of entries popped is the number of lists, because no list repeats a document.
For the shortest window that touches enough lists, feed the merged stream to a sliding window. Keep a count for each list, add the item that came out of the heap, and shrink the window from the left while it still covers need lists.
The same list can appear several times in the window, so store a count, not a yes or no. With the lists [4, 10, 15], [0, 9, 12] and [5, 18, 22], the shortest window that covers all three is 0 to 5. For two lists it is 4 to 5.
A stream with no events has no first item. Push a stream only when it has at least one item.
Exercise · Break it: The stream with no events. This merges the streams and returns the stream number of each event, in time order. Find an input where it gives a wrong answer or fails.
import heapq
def merged_sources(streams):
heap = [(s[0], i, 0) for i, s in enumerate(streams)]
heapq.heapify(heap)
order = []
while heap:
t, i, j = heapq.heappop(heap)
order.append(i)
if j + 1 < len(streams[i]):
heapq.heappush(heap, (streams[i][j + 1], i, j + 1))
return orderSolve them in this order. The first is the plain merge with a tie rule. The second counts lists without building the merged list. The third adds a window.
Before you code each problem, write two lines: what one pop does, and what the heap entry holds. If the second line is only a value, you have no tie rule yet.
Give each problem about 30 minutes. Spend the first five on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Four cases come back on every rung. They are a list with no items, a single list, equal values across lists, and one very long list next to short ones. Write one small test for each.
When a solution fails, look at the push after the pop. Most wrong answers on this street lose the last item of a list, or push an item twice.
Checkpoint · K way merge
Q1/5 After you pop the smallest item from the heap of fronts, what do you push?
Answer: B
The heap must hold the front of every list that still has items. The list that gave the popped item has a new front, so its next item goes in.
Q2/5 Two streams both have an event at time 2. How do you make the merged order the same on every run?
Answer: B
The heap compares the time first, and the stream number when the times are equal. Equal times then always leave in stream order.
Q3/5 You need the documents that appear in at least 2 of k sorted lists, and no list repeats a document. How do you count the lists of the smallest document?
Answer: B
Every entry with the same document comes from a different list, so the number of pops is the number of lists. No merged list is built.
Q4/5 What is the largest size the heap reaches when you merge k lists of any length?
Answer: B
The heap holds one front for each list that still has items. It never holds more than k, and the lists can be very long.
Q5/5 The merged stream feeds a window that must cover at least need lists. Why does the window keep a count for each list?
Answer: B
A list may have many items inside the window. Removing one of them must not uncover the list while another one is still inside.
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.