Merge k sorted lists with a heap of their fronts, and find the kth smallest of sorted rows, pair sums and generated sequences.
You are building the "cheapest items" strip of a shopping app. Three warehouses each keep a price list, sorted from the lowest price to the highest. The strip must show the cheapest prices across all three, one after another.
You could join the three lists and sort the result. But a warehouse can hold millions of prices, and the strip needs only the first few. You need the next smallest price, again and again, without sorting everything.
Picture three piles of numbered tickets on a table. Each pile is sorted, with the smallest number on top. You want one sorted line of tickets.
You do not search the piles. You look at the top ticket of each pile, take the smallest one, and look at the new top of that pile. The three tops are the only tickets that can come next. A heap is a fast way to find the smallest of the tops.
Three sorted piles of tickets. Look only at the three tops and take the smallest. Then look at the new top of that pile.
The front of a sorted list is its first item that is not taken yet. The next value of the merged list is always the smallest of the fronts, because every other item is behind a front that is no larger.
So keep the fronts in a min-heap. Pop the smallest, and send it to the output. Then push the next item of the list it came from, which is that list's new front. The heap holds one item for each list that still has values, so it never holds more than k items.
Every entry must also say which list it came from, and where. Otherwise you cannot find the next item after a pop. In code, an entry is a tuple such as (value, list number, position).
Step by step: A heap of three fronts in an array. The animated player loads in your browser.
Predict what happens
Q Three sorted lists have the fronts 4, 1 and 2. You pop the heap of fronts once. Which statement is true?
Answer: B
The heap returns the smallest front, 1. That list has a new front now, so push it. The heap goes back to one item for each list that still has values.
Take three sorted lists: [1, 5, 9], [2, 6, 7] and [4, 8, 10]. Their fronts are 1, 2 and 4.
Pop the 1, and the first list's front becomes 5. Pop the 2, and the second list's front becomes 6. Pop the 4, and the third list's front becomes 8.
Keep going, and the output is 1, 2, 4, 5, 6, 7, 8, 9, 10. Each pop sends one value out, and each push brings in at most one new front. A list that has run out pushes nothing, so the heap shrinks at the end.
To merge sorted lists, hold the front of each in a min-heap. Pop the smallest, then push the next item of its list.
Step by step: Merge three sorted lists with a heap of fronts. The animated player loads in your browser.
Exercise · Predict the output: How big is the heap after each pop?. The three lists are merged with a heap of fronts. After every pop, and after the next front of that list is pushed if there is one, the code prints the heap size. What does it print?
import heapq
lists = [[1, 2], [3], [4, 5, 6]]
heap = [(lst[0], i, 0) for i, lst in enumerate(lists)]
heapq.heapify(heap)
while heap:
value, i, pos = heapq.heappop(heap)
if pos + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][pos + 1], i, pos + 1))
print(len(heap), end=" ")
print()Predict what happens
Q The heap of fronts holds 6, 8 and 9, and 6 is on top. The list that held 6 is [2, 6, 7]. You pop the 6. What is in the heap next?
Answer: B
The pop removes the 6. Its list is [2, 6, 7], and the 7 is the next item, so the 7 is pushed. The list still has a value left, so the heap keeps three items.
Each of the n output values is popped once, and pushed once at most. The heap holds at most k items, so each push or pop costs about log k steps. The merge takes O(n log k) time, and the heap needs only O(k) memory beyond the output.
The size of k matters. With n = 1,000,000 values in k = 8 lists, a pop or a push passes through about 3 levels of the heap, because log2 of 8 is 3. A full sort of all the values makes about 20 comparisons for each value, because log2 of 1,000,000 is close to 20.
Joining the lists one at a time is slower still. Each join walks the whole result so far, so the work grows like n times k.
Often you do not want the whole merge. You want the kth smallest value of many sorted lists. Merge as usual, and stop after k pops.
Take a grid of prices where every row is sorted, and every column is sorted too:
| col 0 | col 1 | col 2 | |
|---|---|---|---|
| row 0 | 1 | 3 | 5 |
| row 1 | 2 | 4 | 8 |
| row 2 | 6 | 7 | 9 |
Each row is a sorted list. The fronts are 1, 2 and 6. Pop four times and the values taken are 1, 2, 3 and 4. The heap then holds 5, 6 and 8, so the 5th smallest is 5, the top.
For the kth smallest of sorted rows, merge as usual and stop after k pops. The top of the heap is then the answer.
Step by step: The 5th smallest of a sorted grid, from its row fronts. The animated player loads in your browser.
Only about k pops and k pushes happen, so the cost is about k log k, whatever the size of the grid. There is a second saving, because the columns are sorted too. A row below the first k rows starts no lower than the first values of the k rows above it, so those k values come out first. The heap can start with only the first k rows.
Exercise · Break it: Starting with only k rows. This function finds the kth smallest value across the rows. It starts the heap with only the first k rows, which is a shortcut for a grid whose columns are sorted too. Here the rows are sorted, but nothing orders one row against another. Find an input where it gives the wrong answer. Every row has at least one value, and k is at most the number of values.
def kth_smallest(rows, k):
heap = [(rows[r][0], r, 0) for r in range(min(k, len(rows)))]
heapq.heapify(heap)
value = 0
for _ in range(k):
value, r, c = heapq.heappop(heap)
if c + 1 < len(rows[r]):
heapq.heappush(heap, (rows[r][c + 1], r, c + 1))
return valuePredict what happens
Q In the grid above, you want the 5th smallest value. After 4 pops, the heap holds 5, 6 and 8. What do you return?
Answer: C
Four values are out: 1, 2, 3 and 4. The next smallest, the top of the heap, is the 5th smallest. You read it without popping it, or you pop it and return it.
The lists can be implicit. Say a shop sells cases and chargers, and a bundle is one of each. Both price lists are sorted: the cases are [1, 4, 8] and the chargers are [2, 3, 10]. You want the 5 cheapest bundles, and each list may hold 100,000 items, which gives 10^10 bundles.
Think of a table with one row for each case. Row i holds the sums cases[i] + chargers[0], then cases[i] + chargers[1], and so on. Every row is sorted, but the table is never built. The heap holds one cell for each row: the sum, the row and the column.
Start with the first column: 3, 6 and 10. Pop the 3, which is the bundle 1 + 2. Push the next sum of its row, 1 + 3 = 4. Pop the 4, push 1 + 10 = 11, and so on.
The first 5 bundles cost 3, 4, 6, 7 and 10.
A table of sums can be merged without being built. Push the first sum of each row, then the next sum of a popped row.
Sometimes the lists are made from the output itself. Take the numbers whose only prime factors are 2, 3 and 5: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16. Every number after 1 is an earlier number times 2, 3 or 5. So there are three sorted lists: the answer times 2, the answer times 3 and the answer times 5.
Keep one pointer into the answer for each factor. The candidates are the three products, and the next number is the smallest one. A pointer moves on once its product has been taken. With only three lists, a small heap or a plain comparison of three values does the job.
Beware of one trap. The number 6 is both 2 times 3 and 3 times 2, so two candidates are equal. Move every pointer whose candidate equals the number you took. If you move only one, the 6 comes out twice.
Exercise · Put it in order: Numbers made only of 2 and 3. Arrange the lines into a function that returns the nth number whose only prime factors are 2 and 3, counting 1 as the first: 1, 2, 3, 4, 6, 8, 9, 12 and so on.
def nth_smooth(n):
ugly = [1]
i2 = i3 = 0
while len(ugly) < n:
nxt = min(ugly[i2] * 2, ugly[i3] * 3)
ugly.append(nxt)
if nxt == ugly[i2] * 2: i2 += 1
if nxt == ugly[i3] * 3: i3 += 1
return ugly[n - 1]
elif nxt == ugly[i3] * 3: i3 += 1Predict what happens
Q In the numbers with only the factors 2, 3 and 5, the next value is 6. The candidates are 2 times 3, 3 times 2 and 5 times 2. Which pointers move on?
Answer: C
The candidates are 6, 6 and 10. Two of them equal the value taken, so both pointers move. If only one moved, the other would offer 6 again next time, and the list would repeat it.
The same heap serves the other way round: keep the best k of a long list. Use a min-heap of size k, so the weakest of the best is on top, and a better item pushes it out.
Many tasks need a tie rule: the higher rating wins, and on equal ratings the track that comes first wins. Put the rule into the entry. Use (rating, minus position).
A lower rating is weaker. For equal ratings, the larger position has the smaller second part, so it is weaker, and it is the one that leaves.
To keep the best k with a tie rule, put the rule in the entry. Rating, then minus position, makes the later track the weaker one.
Step by step: Keep the 3 best of a stream. The animated player loads in your browser.
Exercise · Find the bug: The tie that drops the wrong track. This keeps the k best-rated tracks. When ratings tie, the track that comes first should stay. On some inputs it keeps the wrong tracks. Which line is wrong?
import heapq
def best_tracks(ratings, k):
heap = []
for pos, rating in enumerate(ratings):
heapq.heappush(heap, (rating, pos))
if len(heap) > k:
heapq.heappop(heap)
return sorted(abs(pos) for _, pos in heap)Here is a heap of fronts next to the two other ways to get the next smallest of k sorted lists. Rows that a heap cannot help with are marked.
| Operation | Heap of fronts | Join the lists one at a time | Join all and sort |
|---|---|---|---|
| Push a front | O(log k): one item for each list | Not used | Not used |
| Pop the smallest front | O(log k) | Not used | Not used |
| Peek at the next value | O(1): read the top | O(1) after all joins | O(1) after the sort |
| Build the first heap of k fronts (heapify) | O(k) | Not used | Not used |
| Search for a given value | O(k): a heap has no search order | O(n) | O(log n) once sorted |
| Merge all n values | O(n log k) | O(n k) | O(n log n) |
| Get the first m values | O((k + m) log k) | O(n k): every join must finish first | O(n log n) |
| Extra memory | O(k): the fronts | O(n): the joined list | O(n): the joined list |
The heap of fronts wins when k is small next to n, and when you need only the first values. It does not help when you need to look values up.
Now drive the heap yourself. Each operation runs step by step, and the cost counter shows comparisons and swaps. In this lesson the heap is a heap of fronts, so a pop is followed by a push.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the merger yourself. The lab gives you a StreamMerger class with five streams, numbered 0 to 4. Values are added to the end of a stream one at a time, and each stream must stay sorted. You write five methods: add, next, next_stream, waiting and heap_size.
Four things to take care over:
add rejects a value that is smaller than the last value ever added to that stream, and a stream number outside 0 to 4. It returns false and changes nothing.next removes the smallest front. When two fronts are equal, the lower stream number goes first. Then it pushes the next waiting value of the same stream.heap_size tells the tests how many entries are in the heap, so a version that pushes every value fails.When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a heap of fronts when you have several sorted lists, streams or rows and want the next smallest value, the first few values, or the kth value. It also fits tables of sums and products that are sorted along each row but never stored.
It is the right tool when the lists are too large to join in memory. The heap needs only one item for each list.
If everything already fits in memory and you need all of it sorted, sorting is simpler and as fast. If the lists are not sorted, a heap of fronts gives wrong answers: sort each list first, or choose another method. For two lists, a plain two-pointer merge needs no heap.
When k is nearly as large as n, the heap of fronts holds almost everything, and the saving is gone.
Pushing all the values of all the lists defeats the idea. The heap then holds n items, not k, and the merge costs O(n log n) with n items of memory. Push only the first item of each list.
for lst in lists:
for value in lst: # wrong: the heap now holds every value
heapq.heappush(heap, value)Pushing every value at the start is the classic mistake. The heap then holds n items, not k, and the saving is gone.
After a pop, the list it came from has a new front, and it must be pushed. If you skip that step, the merge runs out of heap early and drops every value that was behind a front.
value, row, col = heapq.heappop(heap)
out.append(value)
# missing: push lists[row][col + 1] when it existsEntries are compared field by field. If two values are equal, the comparison moves on to the next field. When that field is an object that cannot be compared, such as a node, Python raises an error. Put a number between them, such as the list number, so a tie never reaches the object.
heapq.heappush(heap, (value, node)) # fails when two values are equal
heapq.heappush(heap, (value, list_no, node)) # list_no settles every tieFor numbers built from the factors 2, 3 and 5, two candidates can be the same number. Moving only the pointer that was checked first lets the other candidate offer the same number again, so the list contains repeats.
if best == c2: i2 += 1
elif best == c3: i3 += 1 # wrong: the elif skips the second matchIn a table of sums with up to 100,000 rows, pushing the first cell of every row costs O(rows) memory and time even when k is 5. Only the first k rows can hold one of the k smallest, so push min(rows, k) cells.
heap = [(first[i] + second[0], i, 0) for i in range(len(first))] # wrong when k is smallExplain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The heap of fronts
Q1/3 You merge k sorted lists with a heap. What does the heap hold at any time?
Answer: B
The next value of the merge is always the smallest front. So only the fronts are kept, one for each list that still has values.
Q2/3 The lists [1, 5, 9], [2, 6, 7] and [4, 8, 10] are merged. After three pops the output is 1, 2 and 4. What does the heap hold?
Answer: C
Popping 1, 2 and 4 pushed the next item of each list: 5, 6 and 8. The heap holds one item for each list again.
Q3/3 You merge n values from k sorted lists with a heap of fronts. What is the time?
Answer: C
Each of the n values is popped once and pushed once at most. The heap holds at most k items, so each operation costs about log k.
Checkpoint · Stopping early
Q1/3 A grid has sorted rows and sorted columns. You put the first value of each row in a min-heap, and pop twice. The grid is [[1, 3, 5], [2, 4, 8], [6, 7, 9]]. What is the top of the heap now, after pushing the next value of each popped row?
Answer: A
Pop 1, push 3. Pop 2, push 4. The heap holds 3, 4 and 6, so the top, 3, is the 3rd smallest value.
Q2/3 You want the 5th smallest value of a grid with 500 rows. Why can the heap start with only the first 5 rows?
Answer: C
Columns do not fall, so a lower row starts with a value at least as large as the one above it. Five values come out before it, so it cannot hold the 5th smallest.
Q3/3 How much does it cost to find the kth smallest of many sorted rows with a heap, when k is small?
Answer: B
The heap holds at most k items and you pop k times, so the cost is about k log k, whatever the size of the grid.
Checkpoint · Sums, ties and generated lists
Q1/4 Case prices are [1, 4, 8] and charger prices are [2, 3, 10]. You merge the table of sums, one row for each case. The heap holds 3, 6 and 10. You pop the 3, which is 1 + 2. What do you push?
Answer: B
The popped cell is in row 0. Its next cell is the case 1 with the charger 3, a total of 4. The table is never built, but each cell is worked out when it is pushed.
Q2/4 Entries are tuples (value, list number, position). Why is the list number placed before the position?
Answer: B
Tuples compare field by field. A tie in the value goes to the list number, which is a plain number. This also gives a fixed rule: the lower list goes first.
Q3/4 The numbers with only the prime factors 2, 3 and 5 are 1, 2, 3, 4, 5, 6, 8, 9. Why is 7 missing?
Answer: C
A number is allowed when its only prime factors are 2, 3 and 5. 7 is prime and different from all three, so it is not allowed.
Q4/4 Top 3 tracks by rating, with ties going to the track that comes first. Which entry makes a min-heap keep the right tracks?
Answer: B
A lower rating is weaker. With equal ratings the later track has the smaller minus position, so it is the weaker one, and it is the one that leaves.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.