iq.lab
Python starts when a code cell comes near or you run one
09 Heaps and tries

Lesson 2 of 3

Top k and merging

To find the k largest of n numbers, hold only k of them in a min-heap and let the smallest leave. That costs O(n log k). A heap of the k fronts merges k sorted lists, and two heaps facing each other keep the median of a stream.

About 2 hours 30 minutes, with the 4 problems worked in it
By the end you can
  • Find the k largest or the k smallest items with a heap of size k, and say why it costs O(n log k)

  • Pick a min-heap or a max-heap by asking which item leaves next, and build a max-heap from heapq by negating

  • Order heap entries by a key with tuples, with a tiebreaker for equal keys

  • Merge k sorted lists with a heap of their current fronts

  • Keep the median of a stream of numbers with two heaps

Your payments table has a million rows, and the dashboard wants the three biggest orders. In SQL that is ORDER BY amount DESC LIMIT 3. In Python the first thing that comes to mind is sorted(amounts, reverse=True)[:3], which puts a million numbers in order to keep three of them.

There is a cheaper notebook: walk the amounts once and hold only the three biggest seen so far. A new amount either earns a place and pushes out the smallest of the three, or it leaves at once. That is the notebook the last lesson's leaderboard kept for its 2 largest scores: a min-heap, which hands over "the smallest one I am holding" quickly.

This lesson puts heaps to work four ways: the k largest, the k smallest, merging k sorted lists, and the median of a stream. In every one, the question that picks the design is: which item leaves next?

The k largest: keep a small heap

Say we want the k largest numbers of a list, where k is a count that comes with the input (k = 3 for the dashboard). This time the numbers come as one list, of length n. The notebook holds the k largest numbers seen so far. When a new number arrives, the notebook briefly holds k + 1 numbers, and the smallest of those k + 1 cannot be among the k largest, so it leaves.

A reminder from the last lesson. A heap reads a list as a tree: the children of index i sit at 2 * i + 1 and 2 * i + 2. A min-heap is a list kept in heap order: no parent is bigger than its children, so the smallest item always sits at index 0, but the rest is not sorted. heapq.heappush(heap, x) adds x, and heapq.heappop(heap) removes the smallest item and returns it. On a heap of m items each costs O(log m), because an item moves along one path between the top and the bottom, about log₂ m steps long.

The trace walks [4, 1, 7, 3, 8, 5] with k = 3. The list heap is drawn as a row of cells, in the order Python stores it. Before you step through, guess: which three numbers are left at the end, and which of them sits at index 0?

Step throughThe 3 largest with a min-heap
Step 1 of 28
Line 1 is about to run.
import heapq
def k_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap
Names
no names yet
Output
(nothing printed yet)

A min-heap finds the largest numbers. Its top is the weakest number still inside, the first to leave when a bigger one arrives. So once k numbers have arrived, heap[0] is the kth largest so far, after every step.

Check the walk on a new list before we count its cost.

PredictWho stays in the heap?

This is the k-largest walk with k = 2, written without a function. Type exactly what it prints.

import heapq

heap = []
for x in [6, 2, 9, 4, 7]:
    heapq.heappush(heap, x)
    if len(heap) > 2:
        heapq.heappop(heap)
print(heap[0])
print(sorted(heap))

What does it cost? Every number is pushed once, and once the heap is full, every later number also causes one pop. The heap never holds more than k + 1 numbers, so each push or pop is O(log k), where log k is how many times you can halve k before reaching 1 (3 for k = 8). So n numbers cost O(n log k) time and O(k) extra space.

Sorting costs O(n log n). That is more steps, but sorted runs its whole loop inside Python's fast C code, while our loop runs one Python line at a time, so on a list that fits in memory sorting can still finish first. The heap's real win is memory: it reads each number once and keeps only k, so it also works on a stream too big to store. Python's heapq.nlargest(k, nums) runs this same walk and returns the k largest, largest first. In an interview, write the loop first: it shows the notebook and the promise.

Now pick the right notebook, and count the pops.

Quick checkWhich notebook?

You walk a list keeping the 3 largest numbers seen so far. A fourth number arrives, so one of the four must leave. Which notebook lets you add the new number and remove the leaving one in O(log k) time, with k = 3 here?

Choose one answer, then check.

Work it outCounting pops

k_largest from the trace runs on a list of 1,000 numbers with k = 10. How many times does heapq.heappop run? Type a whole number.

pops

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

The first problem asks for one number, the kth largest, with repeated values counted separately. Walk with a min-heap of size k, and when the walk ends, the answer is heap[0]. Say the brute force first: sort from largest to smallest and read index k − 1, or remove the maximum k − 1 times and read the largest left.

mediumHeaps target 25 min

Kth largest number

You get a list of integers nums and a number k. Return the kth largest number: the one at position k, counting from 1, if nums were sorted from largest to smallest.

Repeated values count separately. In [5, 5, 4] the second largest is 5, not 4.

Example 1
Inputnums = [7, 2, 9, 4, 5], k = 2Output7

Sorted from largest: 9, 7, 5, 4, 2. Position 2 holds 7.

Example 2
Inputnums = [6, 3, 6, 1, 6, 2], k = 3Output6

Sorted from largest: 6, 6, 6, 3, 2, 1. The three 6s fill positions 1 to 3.

Example 3
Inputnums = [-5, -1, -8], k = 3Output-8

When k is the length of the list, the answer is the smallest number.

Constraints
  • 1 ≤ k ≤ len(nums) ≤ 105

  • -105 ≤ nums[i] ≤ 105

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

With k = 1 the heap holds one number, the largest so far: the running maximum, kept in a heap. With k equal to the length, nothing is ever popped and heap[0] is the smallest number.

The k smallest: flip the heap with a minus sign

Now we want the k smallest numbers. Ask the deciding question: when a new number makes k + 1, which one leaves? The largest. So the notebook must hand over its largest number, which calls for a max-heap, a heap that keeps its largest item at index 0.

heappush and heappop keep a min-heap, so we use the last lesson's trick and store every number negated: push -x instead of x. Negation flips the order: 8 is bigger than 5, so -8 is smaller than -5. The largest number becomes the smallest entry, at index 0, and -heap[0] reads it back.

The trace keeps the 2 smallest numbers of [5, 2, 8, 1, 9], so the row holds negative numbers. Before you step through, guess which entry leaves when the 8 arrives.

Step throughThe 2 smallest with negated numbers
Step 1 of 27
Line 1 is about to run.
import heapq
def k_smallest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, -x)
if len(heap) > k:
heapq.heappop(heap)
return [-v for v in heap]
Names
no names yet
Output
(nothing printed yet)

Heaps of tuples: order by a key

Real items are not bare numbers. A point has a distance, and an order has an amount and a customer. The heap must order items by a key, the value we compare by, and still carry the item along. The last lesson did this for jobs with (priority, name) tuples, and the same move works for any item: push a tuple, (key, item).

Python compares tuples item by item, the way you put words in alphabetical order: first items first, and only on a tie, the second items. So (2, "bo") is smaller than (5, "al"), and (5, "al") is smaller than (5, "cy"). The trace pushes four pairs and then pops them all, printing each one. Before you step through, guess the order they print in: which of the two pairs with key 5 comes out first?

Step throughTuples leave the heap by key, then by tiebreaker
Step 1 of 21
Line 1 is about to run.
import heapq
heap = []
for pair in [(5, "cy"), (2, "bo"), (5, "al"), (9, "di")]:
heapq.heappush(heap, pair)
while heap:
print(heapq.heappop(heap))
Names
no names yet
Output
(nothing printed yet)

The second item is a tiebreaker: it decides only when the keys are equal, and it must be something Python can compare, such as a number or a string. If a tie ever reaches two objects with no order, such as two linked list nodes, Python raises a TypeError: the trap from the last lesson. The merge section meets exactly that.

Now combine the two tricks. A negated key puts the largest key on top, and the tiebreaker still runs from small to large.

PredictNegated keys with a tiebreaker

Each pair is a distance and a name, and the heap stores the distance negated. Type exactly what this prints.

import heapq

heap = []
for dist, name in [(4, "ann"), (9, "bo"), (1, "cy"), (9, "al")]:
    heapq.heappush(heap, (-dist, name))
print(heapq.heappop(heap))
print(heapq.heappop(heap))
print(-heap[0][0], heap[0][1])

Put a k-smallest walk together with a key.

Put in orderThe k cheapest items

Put the lines in order to build cheapest(items, k). items is a list of (name, price) pairs with different prices, and the function returns the names of the k cheapest items in alphabetical order. heapq is already imported. Indentation is part of each line, and two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • def cheapest(items, k):
    • return sorted(name for _, name in heap)
    • heapq.heappush(heap, (-price, name))
    • heapq.heappop(heap)
    • for name, price in items:
    • if len(heap) > k:
    • heap = []
    • if len(heap) >= k:
    • heapq.heappush(heap, (price, name))

    The next problem asks for the k points closest to the origin, the point [0, 0]. Two things are new. First, compare squared distances: the distance from [x, y] to the origin is the square root of x2 + y2, and the closer point always has the smaller x2 + y2, so skip the square root. Second, the farthest point leaves, so the heap is a max-heap by distance: push the negated squared distance, with the point's index as the tiebreaker.

    mediumHeaps target 25 min

    K closest points to the origin

    A map holds some points, and the list points gives each one as a list [x, y]. Given a number k, find the k points that lie nearest to the origin, the point [0, 0].

    Measure distance in a straight line: from [x, y] to the origin it is the square root of x2 + y2. Return a list of k points, each one the same [x, y] list it was in points, in any order.

    The inputs are chosen so the answer is unique: whenever k is less than the number of points, the kth closest point is strictly closer than the next closest one.

    Example 1
    Inputpoints = [[3, 1], [0, 2], [-1, -1], [2, -2]], k = 2Output[[0, 2], [-1, -1]]

    The squared distances are 9 + 1 = 10, 0 + 4 = 4, 1 + 1 = 2 and 4 + 4 = 8. The two smallest are 2 and 4.

    Example 2
    Inputpoints = [[4, 4], [-1, 6], [0, 0], [3, -5]], k = 3Output[[3, -5], [4, 4], [0, 0]]

    The squared distances are 32, 37, 0 and 34, so only [-1, 6] is left out. The origin itself is at distance 0. Any order of the three points is accepted.

    Example 3
    Inputpoints = [[1, 0], [0, 1], [-1, 0], [5, 5]], k = 3Output[[1, 0], [0, 1], [-1, 0]]

    Three points tie at distance 1, and all three are in the answer, so the tie decides nothing.

    Constraints
    • 1 ≤ k ≤ len(points) ≤ 3 × 104

    • -104 ≤ x, y ≤ 104

    • The answer is unique.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Kth largest used a min-heap and this one uses a max-heap, and both follow one rule: the top of the heap is the item that leaves next. If an interviewer asks why the two differ, that sentence is the answer.

    Merging k sorted lists: a heap of the fronts

    You have k lists, each sorted, and you want one sorted list of everything: say [3, 8], [1, 4, 9] and [2, 5]. Which values could come first in the merged list? Only the fronts. Each list is sorted, so its smallest value not yet taken is at its front, and the next value of the result is the smallest of at most k fronts.

    After we take a value, only one front changes: the list we took from moves forward by one. Taking the smallest again and again while one replacement arrives each time is what a heap does. Each entry is a tuple (value, i, j): the value, i, which list it came from, and j, its position in that list, so we can find that list's next value. Both count from 0, as indexes do, so list 1 is [1, 4, 9].

    heapq.heapify(heap), from the last lesson, rearranges a list into heap order, in place, in O(k) for k items. We use it once, on the fronts. The trace merges the three lists above. Before you step through, guess the most entries the heap ever holds.

    Step throughMerging 3 sorted lists with a heap of fronts
    Step 1 of 51
    Line 1 is about to run.
    import heapq
    def merge_sorted(lists):
    heap = []
    for i, values in enumerate(lists):
    if values:
    heap.append((values[0], i, 0))
    heapq.heapify(heap)
    out = []
    while heap:
    value, i, j = heapq.heappop(heap)
    out.append(value)
    if j + 1 < len(lists[i]):
    heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out
    Names
    no names yet
    Output
    (nothing printed yet)

    When you need only the start of the merged order, stop early.

    Code itThe kth smallest across sorted lists

    Write kth_smallest_across(lists, k). lists holds sorted Python lists (some may be empty), and k is between 1 and the total number of values. Return the kth smallest value of all the lists together, with repeats counted separately. Here k is the rank you want (k = 1 is the smallest), not the number of lists. Do not merge everything: stop as soon as you have the answer. Then press Watch it run to see the heap of fronts change.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
    Quick checkWhy log k?

    k sorted lists hold N values in total. The heap merge costs O(N log k), not O(N log N). Why?

    Choose one answer, then check.

    The problem gives the lists as linked lists: chains of ListNode objects, each with a value val and a pointer next to the following node, where the last next is None. The heap entry becomes (node.val, i, node): the node replaces the position, and node.next is that list's next node. Here i is required: two nodes cannot be compared, so a tie on value must stop at i, which is unique because each list has at most one entry in the heap. Build the result behind a dummy head, a placeholder node in front of the answer, with a tail pointer to the last node attached. Name the brute force first: copy every value into one Python list and sort it, O(N log N), or scan all k fronts for every value, O(N × k).

    hardHeapsLinked lists target 40 min

    Merge k sorted lists

    Several sorted linked lists need to become one. The list lists holds k linked lists, and the values in each one run from smallest to largest. Combine them into a single linked list that holds every value, also running from smallest to largest with every repeated value kept, and return its head. When there are no nodes at all, return None.

    A linked list is a chain of ListNode objects. Each node has a value val and a pointer next to the following node, and the last node's next is None. A linked list is passed around as its first node, its head, and an empty linked list is None. You may reuse the nodes you are given.

    The examples write each linked list as the list of its values.

    Example 1
    Inputlists = [[2, 6, 9], [1, 7], [3, 4, 8]]Output[1, 2, 3, 4, 6, 7, 8, 9]

    Each step takes the smallest value at the front of any list: 1 from the second list, then 2 from the first, then 3 from the third, and so on.

    Example 2
    Inputlists = [[], [5, 5], []]Output[5, 5]

    Empty lists add nothing, and both 5s stay.

    Example 3
    Inputlists = []Output[]

    No lists at all, so the result is empty: return None.

    Constraints
    • 0 ≤ k = len(lists) ≤ 104

    • Each linked list has 0 to 500 nodes and is sorted from smallest to largest.

    • At most 105 nodes in total.

    • -105 ≤ val ≤ 105

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Each node enters and leaves the heap once: O(N log k) time again, and O(k) extra space because the nodes are reused, not copied. If asked to do it without a heap, merge the lists in pairs, round after round, as merge sort does. Each round walks all N nodes and halves the number of lists, so about log₂ k rounds: O(N log k) again.

    The median of a stream: two heaps

    Numbers arrive one at a time, and at any moment someone may ask for the median: the middle number once they are sorted, or the average of the two middle numbers when the count is even. For 2, 4, 7, 9 it is (4 + 7) / 2 = 5.5. With n numbers so far, sorting them for every question costs O(n log n) each time. Keeping the numbers in a sorted list makes the question cheap, but each new number must be slotted into place, shifting the ones after it: O(n) per number.

    The median needs only the middle. Cut the sorted numbers into a smaller half and a larger half, giving the smaller half the extra number when the count is odd. Then the median is the largest of the smaller half, or, for an even count, the average of that and the smallest of the larger half. For 2, 4, 7, 9 the halves are 2, 4 and 7, 9. Add a 5, and they become 2, 4, 5 and 7, 9: the median is 5, the largest of the smaller half.

    So keep two heaps facing each other. low holds the smaller half as a max-heap, stored negated, so -low[0] is its largest. high holds the larger half as a min-heap, so high[0] is its smallest. Two rules keep the tops right. Order: every number in low is at most every number in high. Balance: low holds as many numbers as high, or one more.

    Adding a number takes three moves. Push it into low. Move the largest of low up into high, which restores the order rule whatever the new number was. If high now holds more numbers than low, move its smallest back down. The trace adds 4, 9, 2 and 7 and prints the median after each. Before you step through, work out the four medians yourself.

    Step throughA running median with two heaps
    Step 1 of 33
    Line 1 is about to run.
    import heapq
    def running_medians(nums):
    low = []
    high = []
    for num in nums:
    heapq.heappush(low, -num)
    heapq.heappush(high, -heapq.heappop(low))
    if len(high) > len(low):
    heapq.heappush(low, -heapq.heappop(high))
    if len(low) > len(high):
    print(-low[0])
    else:
    print((-low[0] + high[0]) / 2)
    Names
    no names yet
    Output
    (nothing printed yet)

    Move 2 always happens, even when the new number belongs in low, as the 2 did. It restores the order rule without our code comparing any values. Only the new number can break the rule. If it is the largest in low, move 2 carries it up, and low is back to its old numbers. If not, it is at most the old largest, which was already at most everything in high. Move 3 is safe too: the smallest of high is at least everything in low, so it can join low without breaking the order.

    Run the three moves by hand once before the problem.

    On paperTwo heaps by hand

    On paper, add 6, 1, 3 and 10 to two empty halves with the three moves: push into low; move the largest of low up into high; if high now holds more numbers than low, move the smallest of high back down. After each number, write both halves as sorted lists of plain numbers (not negated) and the median. Reveal one step at a time to check.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    median after adding 10

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The problem wraps the moves in a class: add_num does the three moves, and find_median reads the two tops and removes nothing. Keep both heaps on the object, as self.low and self.high created in __init__ (the method that runs once when the object is made), so two finders never share numbers.

    hardHeapsDesign as coding target 40 min

    Median of a stream

    Numbers arrive one at a time, and at any moment you may be asked for the median of all the numbers so far. The median is the middle number once the numbers are sorted. With an even count there are two middle numbers, and the median is their average: for 1, 3, 4, 8 it is (3 + 4) / 2 = 3.5.

    Write a class MedianFinder:

    • MedianFinder() starts with no numbers.
    • add_num(num) records one integer num.
    • find_median() returns the median of every number recorded so far and removes nothing. It is only called after at least one add_num.

    For an even count, return the average as Python's / gives it, a float such as 3.5 or 3.0. For an odd count, return the middle number; an int and a float with the same value both pass. Both methods are called many times, so both must stay fast.

    Example 1
    InputMedianFinder(), then add_num(5), find_median(), add_num(1), find_median(), add_num(8), find_median(), add_num(2), find_median()Output5, 3.0, 5, 3.5

    The sorted numbers are [5], then [1, 5], then [1, 5, 8], then [1, 2, 5, 8]. The medians are 5, (1 + 5) / 2, 5, and (2 + 5) / 2.

    Example 2
    InputMedianFinder(), then add_num(-3), add_num(4), find_median()Output0.5

    (-3 + 4) / 2 = 0.5. Negative numbers and medians that are not whole numbers are both fine.

    Constraints
    • -105 ≤ num ≤ 105

    • At most 5 × 104 calls in total.

    • find_median is called only after at least one add_num.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    add_num costs O(log n) and find_median costs O(1). The extension to expect, a median of only the last w numbers, needs numbers to leave from the middle of a heap, and the problem's follow-ups sketch how.

    This module's practice bank has two more from this family. Jobs with a cooldown (LeetCode 621) keeps a max-heap of how many jobs of each kind are left. Most searched words (LeetCode 692) counts the words in a dict, then pops (-count, word) pairs, so equal counts come out in alphabetical order.

    Last, say it the way you would in the room.

    Say itSay it like you would in the room

    An interviewer asks: "A log holds one duration per request and is far too big to load into memory. Return the 100 largest durations." Explain your approach as you would before typing: the walk, the notebook, the promise, the cost, and why you chose a min-heap.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Tries