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

Lesson 1 of 3

How a heap works

A heap is a list read as a tree, kept in an order where the smallest item always sits at index 0. Push and pop each walk one path of that tree, so both cost O(log n), and Python's heapq does the walking for you.

About 1 hour 35 minutes, with the 2 problems worked in it
By the end you can
  • Find the parent and the children of any index in a heap stored as a list

  • Trace a push (append, then swap up) and a pop (move the last item to the top, then swap down) by hand

  • Explain why push and pop cost O(log n) and why heapify costs O(n)

  • Use heapq as a min-heap, negate values to take the largest first, and use tuples for priorities

  • Keep the k largest items of a stream in a min-heap of size k

Your pipeline runs jobs from a waiting list. Each job has a priority number, and the smallest number runs first. Jobs keep arriving, and each time a worker frees up it asks: which waiting job has the smallest number?

The lists you know are each slow at half of the work. An unsorted list takes a new job with append, but must scan every job to find the smallest. A list sorted largest first hands over the smallest with pop() from its end, but a new job must be slotted into place, shifting every job after it one slot. Module 3 showed that shifting costs O(n): work that grows in step with n, the number of jobs. O(1) means a fixed amount of work, however many jobs wait.

notebookadd a jobtake the smallest job
unsorted listO(1): appendO(n): scan every job
sorted list, largest firstO(n): shift to make roomO(1): pop from the end
heapO(log n)O(log n)

A heap does both in O(log n). log₂ n is how many times you can halve n before you reach 1: about 20 for a million. So with a million waiting jobs, each add or take costs a few dozen comparisons, not a million.

A tree stored in a list

Where does a heap keep its items? In an ordinary Python list, read as a tree. A tree, here, is items joined by parent and child links: one item at the top, called the root, and at most two children under each item. Each row is a level, counted from 0 at the root.

Read the tree level by level, left to right, and write the items down in that order: that is the list. The root is index 0, its children are indexes 1 and 2, and theirs are 3 to 6. A list has no gaps, so neither does the tree: every level is full before the next one starts, and the last level fills from the left. A tree with no gaps like this is called complete.

No links are stored. Arithmetic finds them. For the item at index i:

  • its children are at 2 * i + 1 and 2 * i + 2,
  • its parent is at (i - 1) // 2.

Why those numbers? After the root, child slots go out two at a time, in index order: index 0's children take indexes 1 and 2, index 1's take 3 and 4, index 2's take 5 and 6. Before index i come i items, which use up 2 × i slots after the root, so the children of index i start at 2 × i + 1. The parent formula runs that backwards.

// divides and drops the remainder. So the parent of index 4 is (4 − 1) // 2 = 1, and the children of index 1 are 3 and 4. A child index past the end of the list means that child does not exist.

A min-heap adds one promise: no parent is bigger than its children. Follow parents upward from anywhere: the values never grow, and every path ends at index 0. So the smallest item is always at index 0, and reading it costs O(1). A max-heap makes the opposite promise. We build min-heaps, because that is what heapq, Python's built-in heap module, keeps.

The widget draws one heap twice, as a tree and as the list that stores it, with each item's index under it. It starts from 5, 3, 8 and 1, added one at a time with the push you will meet in the next section.

Two quick checks: the arithmetic, then the promise.

Work it outWhose child is the last item?

A heap is stored in a list of 12 items, at indexes 0 to 11. What is the index of the parent of the last item? Type a whole number.

parent index

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

Quick checkWhich list is a min-heap?

Which of these lists keeps the min-heap promise, that no parent is bigger than its children? Check each index against its parent at (i - 1) // 2.

Choose one answer, then check.

Push and pop: one path each

How do you add or take out an item without breaking the promise? Each move breaks the promise in one spot, then repairs it along one path of the tree.

Push: append, then swap up

A push must keep the tree complete and keep the promise. The only spot that leaves no gap is the end of the list. But the new item may be smaller than its parent there, which breaks the promise on that one link. So swap it with its parent, and keep swapping up while it is smaller. Here is the code, on the widget's heap and the same 2. Before you step through, guess: at which index does 2 stop?

Step throughPush 2: append, then swap up
Step 1 of 17
Line 1 is about to run.
def push(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[i] >= heap[parent]:
break
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
heap = [1, 3, 8, 5]
push(heap, 2)
print(heap)
Names
no names yet
Output
(nothing printed yet)

One link at a time is enough. Before each check, the promise holds everywhere except, possibly, between the new item and its parent. Say they swap. The old parent moves down into the new item's place. Everything under that place was already under the old parent before the push, so the old parent is no bigger than any of it. The new item moves up. It is smaller than the old parent, so it is also smaller than the old parent's other child.

So after a swap, only the link above the new item can be wrong. When the new item is not smaller than its parent, or reaches index 0, the promise holds everywhere. This move is called sifting up.

heapq.heappush(heap, x) makes the same move. Predict what it leaves behind.

PredictWhere does the 3 stop?

heapq.heappush makes the push you watched: append, then swap up while the new item is smaller than its parent. Type exactly what this prints.

import heapq

heap = [2, 4, 6, 7, 9]
heapq.heappush(heap, 3)
print(heap)

Now write the mirror image yourself, for a heap that keeps the largest on top.

Code itPush onto a max-heap

A max-heap makes the opposite promise: every parent is at least as big as its children, so the largest item is at index 0. Write push_max(heap, x), which adds x to a max-heap stored in the list heap and keeps that promise. Change the list in place; return nothing. Then press Watch it run to see x climb.

⌘+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.

Pop: move the last item up, then swap down

The smallest item is at index 0, so a pop starts by taking it. That leaves a hole at the top. Deleting index 0 would shift every other item one slot left: O(n) work, and about half the items would end up under a different parent, so the promise could break in many places at once. So the last item fills the hole: removing the end of a list is O(1), and the tree stays complete.

The item now on top came from the bottom, so it is probably too big for its place. So swap it down: compare it with its smaller child, and swap while it is bigger. Why the smaller child? It moves up, and it is no bigger than its sibling (the other child of the same parent) or the item that moved down, so both of its new links keep the promise. Guess first: the heap is [1, 3, 2, 7, 4, 5, 9]. After the pop, which number is on top, and at which index does 9 land?

Step throughPop: take the top, move the last item up, swap down
Step 1 of 30
Line 1 is about to run.
def sift_down(heap, i):
while 2 * i + 1 < len(heap):
child = 2 * i + 1
right = child + 1
if right < len(heap) and heap[right] < heap[child]:
child = right
if heap[i] <= heap[child]:
break
heap[i], heap[child] = heap[child], heap[i]
i = child
def pop_min(heap):
smallest = heap[0]
last = heap.pop()
if heap:
heap[0] = last
sift_down(heap, 0)
return smallest
heap = [1, 3, 2, 7, 4, 5, 9]
print(pop_min(heap))
print(heap)
Names
no names yet
Output
(nothing printed yet)

Line 15 covers a heap of one item. There, heap.pop() removes the only item, which smallest already holds, and leaves the list empty: no hole to fill, nothing to sift.

This move is called sifting down. To see it on a tree, bring the widget back to [1, 3, 8, 5] with Reset and press Pop min: the 5 from index 3 jumps to the top and sinks to index 1.

Why both moves cost O(log n). Levels fill one at a time, and level d holds up to 2d items: 1, 2, 4, 8. So 15 items fill 4 levels, and a million items fill only 20. Push walks one path up and pop walks one path down, with at most one swap per level.

Recap. A heap is a list read as a tree, with no parent bigger than its children. Push appends and swaps up. Pop takes index 0, moves the last item to the top and swaps it down. Each walks one path: O(log n).

Try a pop on paper, then put the sift-down lines in order.

On paperPop by hand

Pop the smallest item from the heap [2, 3, 6, 5, 4, 8, 9] by hand, the way the trace did. Draw the tree if it helps: index 0 on top, indexes 1 and 2 below it, then indexes 3 to 6. Write the list after every swap. At which index does 9 end up?

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.

index where 9 ends

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

Put in orderPut sift down together

Put the lines in order to build sift_down(heap, i): while the item at i has a child, find the smaller child, stop if the item is not bigger than it, otherwise swap and follow the item down. Indentation is part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • child = (i - 1) // 2
    • if heap[right] < heap[child]:
    • i = child
    • right = child + 1
    • if right < len(heap) and heap[right] < heap[child]:
    • child = 2 * i + 1
    • break
    • while 2 * i + 1 < len(heap):
    • heap[i], heap[child] = heap[child], heap[i]
    • if heap[i] <= heap[child]:
    • child = right
    • def sift_down(heap, i):

    Building a heap all at once

    What if every item is there before the first pop? Pushing n items one at a time costs O(n log n) in all. heapify (heapq.heapify in Python) does better: it sifts down every parent, from the last parent back to the root. A parent here is any item with at least one child. With n items, the last parent is at index n // 2 − 1: any later index i has its first child at 2 × i + 1 ≥ n, past the end.

    Working from the back means the items under a parent already form heaps when its turn comes (a lone item with no children is a heap of one). So one sift down of that parent turns it and everything under it into a heap. When index 0 is done, the whole list is a heap. Guess before you step: what does [5, 3, 8, 1] become?

    Step throughheapify: sift down every parent, last one first
    Step 1 of 37
    Line 1 is about to run.
    def sift_down(heap, i):
    while 2 * i + 1 < len(heap):
    child = 2 * i + 1
    right = child + 1
    if right < len(heap) and heap[right] < heap[child]:
    child = right
    if heap[i] <= heap[child]:
    break
    heap[i], heap[child] = heap[child], heap[i]
    i = child
    def heapify(heap):
    for i in range(len(heap) // 2 - 1, -1, -1):
    sift_down(heap, i)
    heap = [5, 3, 8, 1]
    heapify(heap)
    print(heap)
    Names
    no names yet
    Output
    (nothing printed yet)

    Why O(n) and not O(n log n). About half the items are leaves, items with no children, and heapify never sifts them. Only the root can sink the whole height. The table counts the most swaps each item can cause in a heap of 15 items, which fills 4 levels exactly: sinking in heapify, or climbing when it is pushed.

    levelitems theremost swaps each, heapifymost swaps each, pushing
    0 (the root)130
    1221
    2412
    3 (the bottom)803
    all 15 items3 + 4 + 4 + 0 = 110 + 2 + 8 + 24 = 34

    heapify spends the fewest moves where most items are. Pushing does the opposite: every item on the bottom level can climb to the top. The order 15, 14, ..., 1 forces every one of those swaps: heapify makes 11 and the pushes make 34. For any size, heapify's total stays below n swaps, so it is O(n).

    Python's heapq makes all three moves on a plain list. heapq.heapify(nums) rearranges nums in place, heapq.heappush(heap, x) pushes, heapq.heappop(heap) removes and returns the smallest, and heap[0] reads the smallest without removing it. There is no heap object: the list is the heap, and the promise holds only while every change goes through heapq. Run this: the first two lists match the heapify and push traces.

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    The pop takes the 1, moves the 3 from the end to the top, and swaps it with its smaller child, 2: the heap is [2, 3, 8, 5]. The last line reads the new smallest, 2, and leaves it in the heap. On an empty heap, both heap[0] and heappop raise IndexError, so check if heap: first when the heap can run out.

    Quick checkThe cheapest way to build

    You have a list nums of 1,000,000 numbers, all there before the first pop, and you need a min-heap of them. Which way costs the least?

    Choose one answer, then check.

    Choosing what comes out first

    What if the largest should come out first, or each entry is a job with a priority? A heap always hands back its smallest entry first. To change the order, change what you store: negated numbers, or tuples.

    Largest first: store negatives

    heappush and heappop keep a min-heap. Python 3.14, which this lab runs, added max-heap versions such as heapq.heappush_max, but older versions lack them, and the interview pad may run one. The trick that works on every version: store each number negated. 30 is bigger than 25, so -30 is smaller than -25: the largest number becomes the smallest entry and comes out first. Flip its sign back as it comes out. Guess biggest and second before you step through.

    Step throughLargest first, by storing negatives
    Step 1 of 12
    Line 1 is about to run.
    import heapq
    orders = [12, 30, 7, 25]
    heap = [-x for x in orders]
    heapq.heapify(heap)
    biggest = -heapq.heappop(heap)
    second = -heapq.heappop(heap)
    print(biggest, second)
    Names
    no names yet
    Output
    (nothing printed yet)
    PredictWatch the signs

    Type exactly what this prints. Watch the signs.

    import heapq
    
    heap = []
    for x in [4, 10, 3]:
        heapq.heappush(heap, -x)
    print(heap[0])
    print(-heapq.heappop(heap), -heapq.heappop(heap))
    

    Now a full problem that needs the two heaviest stones, round after round, from a pile that changes every round.

    easyHeaps target 15 min

    Last stone weight

    A pile of stones lies on a table, and the list stones holds their weights. A round goes like this: take the two heaviest stones off the pile and crash them into each other. If they weigh the same, both turn to dust. If not, the lighter one turns to dust and the heavier one loses as much weight as the lighter one had: stones of 7 and 3 leave one stone of 4, which goes back on the pile.

    Keep playing rounds while two or more stones are on the pile. Then return the weight of the stone that is left, or 0 if the pile is empty. Leave the list stones itself unchanged.

    Example 1
    Inputstones = [4, 10, 3, 7]Output2

    Smash 10 and 7: a 3 goes back, so the pile is 4, 3, 3. Smash 4 and 3: a 1 goes back, so the pile is 3, 1. Smash 3 and 1: a 2 is left alone.

    Example 2
    Inputstones = [5, 5]Output0

    Equal stones destroy each other, so nothing is left.

    Example 3
    Inputstones = [9]Output9

    One stone needs no round.

    Constraints
    • 1 ≤ len(stones) ≤ 3 × 104

    • 1 ≤ stones[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.

    Each round is two pops and at most one push, O(log n) each: O(n log n) for the whole game, where a fresh max scan every round costs O(n2) in all. The leftover stone goes back through heappush, so it can be the heaviest again next round.

    Priorities: store tuples

    A heap can order records when each record is a tuple. Python compares tuples item by item: the first items decide, and only a tie looks at the second items. So push (priority, name) pairs, and the smallest priority comes out first. Two jobs below share priority 1: guess which of them comes out first, then run it.

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    Both priority 1 jobs come out first, but "clean" comes out before "extract", although it arrived later: on the tie, Python compared the names, and "c" comes before "e".

    Here is that counter in code. Predict which job wins the tie now.

    PredictWho wins the tie now?

    Each entry is now (priority, arrival, name), with arrival counting up from 0, and entry[2] is the name. Type exactly what this prints, one name per line.

    import heapq
    
    jobs = []
    arrival = 0
    for priority, name in [(2, "load"), (1, "extract"), (1, "clean")]:
        heapq.heappush(jobs, (priority, arrival, name))
        arrival += 1
    while jobs:
        entry = heapq.heappop(jobs)
        print(entry[2])
    

    Keeping only the k largest

    How do you track the kth largest of numbers that keep arriving, meaning the kth one when they are sorted largest first? A leaderboard shows the 2nd highest score so far. It already holds two scores, 4 and 9, and more keep arriving.

    Once two scores beat a score, it can never be 2nd again: scores only arrive, so it can only sink. So keep only the 2 largest scores, in a min-heap. Its top is the smaller of the two: exactly the 2nd largest. When a new score arrives, push it, then pop the smallest of the three. Before stepping, guess the three numbers this prints.

    Step throughKeeping only the 2 largest scores
    Step 1 of 20
    Line 1 is about to run.
    import heapq
    k = 2
    top = [4, 9]
    for score in [2, 6, 12]:
    heapq.heappush(top, score)
    if len(top) > k:
    heapq.heappop(top)
    print(top[0])
    Names
    no names yet
    Output
    (nothing printed yet)

    For any k, the rule is the same: keep the k largest in a min-heap, and its top is the kth largest.

    A min-heap, although we want large scores, because both jobs, reading the kth largest and choosing who leaves, need the smallest kept score.

    The full problem wraps this in a class: the constructor (__init__, which runs once when the board is made) takes the starting scores, and add records one score and returns the kth largest.

    easyHeapsDesign as coding target 15 min

    Kth largest in a stream

    A game's leaderboard shows one number: the score at rank k, meaning the kth largest score recorded so far. Scores keep arriving, and the board must update after each one.

    Write a class KthLargest:

    • KthLargest(k, nums) receives k and the list nums of scores recorded so far. It may hold fewer than k scores, or many more. Do not change nums.
    • add(val) takes one more score, val, and returns the score that now sits at rank k.

    The kth largest is the score at position k, counting from 1, when every score is sorted from largest to smallest. Repeated scores count separately: with scores 6, 6, 4, the second largest is 6. Every call to add leaves at least k scores recorded.

    Example 1
    InputKthLargest(2, [5, 1, 7]), then add(3), add(8), add(6), add(9)Output5, 7, 7, 8

    After add(3) the scores from largest are 7, 5, 3, 1, so the second largest is 5. The 8 makes it 7. The 6 lands below the 7, so it stays 7. The 9 makes it 8.

    Example 2
    InputKthLargest(3, [4, 4]), then add(4), add(6), add(6), add(7)Output4, 4, 4, 6

    Repeats count separately. After the second 6 the scores are 6, 6, 4, 4, 4, so the third largest is still 4. After the 7 they start 7, 6, 6, so it is 6.

    Example 3
    InputKthLargest(1, []), then add(-3), add(-5), add(2)Output-3, -3, 2

    With k = 1 the answer is the largest score so far. Scores can be negative.

    Constraints
    • 1 ≤ k ≤ 104

    • 0 ≤ len(nums) ≤ 105

    • -105 ≤ nums[i], val ≤ 105

    • At most 3 × 104 calls to add.

    • At least k scores are recorded after each add.

    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.

    The constructor trims the heap to k scores; add pushes, then pops when the heap holds k + 1. Each add is O(log k), and the heap stays at k scores however long the stream runs.

    Last, practice that answer out loud.

    Say itWhat does a push cost?

    An interviewer watches you call heapq.heappush and asks: "What does that cost, and why?" Write what you would say: how the heap is stored, the promise it keeps, what a push does, and the cost.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Top k and merging