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.
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.
| notebook | add a job | take the smallest job |
|---|---|---|
| unsorted list | O(1): append | O(n): scan every job |
| sorted list, largest first | O(n): shift to make room | O(1): pop from the end |
| heap | O(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 + 1and2 * 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.
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.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
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?
def push(heap, x):heap.append(x)i = len(heap) - 1while i > 0:parent = (i - 1) // 2if heap[i] >= heap[parent]:breakheap[i], heap[parent] = heap[parent], heap[i]i = parentheap = [1, 3, 8, 5]push(heap, 2)print(heap)
(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.
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.
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.
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?
def sift_down(heap, i):while 2 * i + 1 < len(heap):child = 2 * i + 1right = child + 1if right < len(heap) and heap[right] < heap[child]:child = rightif heap[i] <= heap[child]:breakheap[i], heap[child] = heap[child], heap[i]i = childdef pop_min(heap):smallest = heap[0]last = heap.pop()if heap:heap[0] = lastsift_down(heap, 0)return smallestheap = [1, 3, 2, 7, 4, 5, 9]print(pop_min(heap))print(heap)
(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.
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.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
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.
Add lines from the list below, in order.
child = (i - 1) // 2if heap[right] < heap[child]:i = childright = child + 1if right < len(heap) and heap[right] < heap[child]:child = 2 * i + 1breakwhile 2 * i + 1 < len(heap):heap[i], heap[child] = heap[child], heap[i]if heap[i] <= heap[child]:child = rightdef 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?
def sift_down(heap, i):while 2 * i + 1 < len(heap):child = 2 * i + 1right = child + 1if right < len(heap) and heap[right] < heap[child]:child = rightif heap[i] <= heap[child]:breakheap[i], heap[child] = heap[child], heap[i]i = childdef 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)
(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.
| level | items there | most swaps each, heapify | most swaps each, pushing |
|---|---|---|---|
| 0 (the root) | 1 | 3 | 0 |
| 1 | 2 | 2 | 1 |
| 2 | 4 | 1 | 2 |
| 3 (the bottom) | 8 | 0 | 3 |
| all 15 items | 3 + 4 + 4 + 0 = 11 | 0 + 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.
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.
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.
import heapqorders = [12, 30, 7, 25]heap = [-x for x in orders]heapq.heapify(heap)biggest = -heapq.heappop(heap)second = -heapq.heappop(heap)print(biggest, second)
(nothing printed yet)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.
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.
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.
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.
import heapqk = 2top = [4, 9]for score in [2, 6, 12]:heapq.heappush(top, score)if len(top) > k:heapq.heappop(top)print(top[0])
(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.
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.
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.
Saved in this browser as you type.