Picture a heap as a tree and as an array, push and pop with sift up and sift down, build one with heapify, keep the best k of a stream, and build your own min-heap.
You are building the waiting list for a hospital triage desk. Patients arrive all day, and a nurse gives each one an urgency number: 1 is the most urgent. The next patient to see the doctor is always the one with the smallest number, not the one who arrived first.
A plain queue cannot do that, because a queue serves people in the order they came. You need a collection where you add items in any order and always get the most urgent one back.
Think of the nurse's desk. A person with a sprained ankle arrives first. Then someone with chest pain walks in. The doctor asks for the next patient, and the nurse sends the chest pain case, because it is more urgent.
The desk does not sort every patient each time one arrives. It only needs to know who is most urgent right now, and it needs that answer fast.
A hospital triage desk always sends in the most urgent patient, not the first one to arrive. That is a priority queue.
A priority queue is a collection with two main jobs. Push adds an item with its priority. Pop removes and returns the most urgent item. A peek looks at the most urgent item without removing it.
You choose the meaning of urgent. In a min-heap the smallest value is the most urgent. In a max-heap the largest value is. Everything in this lesson uses a min-heap, and a max-heap is the same with the comparisons turned round.
A heap is the usual way to build a priority queue. It is a binary tree, with at most two children for each node, that follows two rules.
The order rule is weaker than a search tree's. A heap does not keep its items sorted. It only promises that each parent beats its children, which is enough to keep the best item on top.
Step by step: A heap in an array. The animated player loads in your browser.
Predict what happens
Q A min-heap holds 10 at the top, with 20 and 15 as its two children. Which statement about the tree must be true?
Answer: B
The order rule only compares a parent with its children. 10 is the smallest, so it is on top. The two children are in no fixed order with each other.
Because a heap is complete, you can store it in a plain array without a single pointer. Write the items level by level, from the left, into cells 0, 1, 2, and so on. The root is cell 0, its children are cells 1 and 2, and the next level is cells 3 to 6.
The links become arithmetic. For the item at index i:
(i - 1) // 22i + 12i + 2Check it on cell 4. Its parent is at (4 - 1) // 2, which is 1, and its children would be cells 9 and 10. The array uses one cell for each item, and no memory for links.
A heap lives in an array. For index i, the parent is at i minus one, halved. The children are at two i plus one and plus two.
Exercise · Break it: The heap check that skips a child. This function checks that an array is a valid min-heap, but it compares each parent with only one of its children. Find an array where it gives the wrong answer.
def is_min_heap(cells):
n = len(cells)
for i in range(n):
left = 2 * i + 1
if left < n and cells[left] < cells[i]:
return False
return TrueThe smallest item is always at index 0, so a peek reads one cell. It costs O(1).
To add an item, put it in the first free cell at the end of the array. That keeps the tree complete. But the new item may be smaller than its parent, which breaks the order rule.
Fix it by sifting up. Compare the item with its parent. If the item is smaller, swap them, and repeat from the parent's cell. Stop when the parent is not larger, or when the item reaches the top.
The item climbs one level at each swap. A complete tree is as short as a tree can be, because each level holds twice as many items as the one above. So 1,000 items fit in 10 levels, and a million in about 20. That is about log n levels, so a push costs at most about log n swaps.
A push adds the item at the end, then sifts it up, swapping with its parent while smaller. It follows one path, so it costs the height.
Step by step: Push 5 into a min-heap. The animated player loads in your browser.
Step by step: Push 50, which is larger than everything. The animated player loads in your browser.
Predict what happens
Q A min-heap holds the array 10, 20, 15, 30, 40, 25, 18. You push 5. Where does 5 end up?
Answer: C
5 starts in cell 7. Its parent is cell 3 (30), then cell 1 (20), then cell 0 (10). At each step 5 is smaller, so it swaps and climbs three levels to the top.
The smallest item is the top. To remove it, you cannot leave a hole at the root. So take the last item of the array, move it to cell 0, and shorten the array by one. The tree is complete again, but the new top is probably too large.
Fix it by sifting down. Compare the item with its two children. If a child is smaller, swap it with the smaller child, and repeat from that cell. Stop when neither child is smaller, or when the item has no children.
Picking the smaller child matters. The smaller child becomes the new parent of the other one, so the order rule still holds between them.
The item sinks one level at each swap, so a pop costs at most about log n swaps, the height of the tree.
A pop returns the top, moves the last item up, and sifts it down, swapping with the smaller child. It follows one path, so it costs the height.
Step by step: Pop the smallest. The animated player loads in your browser.
Exercise · Put it in order: Sinking the new top. Arrange the lines into a function that sifts the item at cell i down inside the first n cells of a min-heap, and returns the array.
def sift_down(cells, i, n):
while 2 * i + 1 < n:
child = 2 * i + 1
if child + 1 < n and cells[child + 1] < cells[child]:
child += 1
if cells[i] <= cells[child]:
break
cells[i], cells[child] = cells[child], cells[i]
i = child
return cells
child = 2 * iPredict what happens
Q A min-heap holds 10, 20, 15, 30, 40, 25, 18. You pop. After the pop, what is the top?
Answer: C
The 10 is returned. The last item, 18, moves to cell 0. Its children are 20 and 15, and 15 is smaller, so 15 moves up to the top and 18 sinks into its place.
Suppose you already have n items and want a heap. You could push them one at a time, for n log n work. There is a faster way, called heapify.
Look at the array as a tree. Every leaf is already a heap of one item. So start at the last item that has a child, at index n // 2 - 1, and sift it down. Do the same for each cell before it, back to cell 0, and the whole tree is a heap.
Why is that cheaper? Half the items are leaves and never move. A quarter sink at most one level, an eighth at most two, and so on. Add those up and the total number of swaps stays below n, so heapify costs O(n), not n log n.
Trace it on 40, 30, 50, 20, 10, 60, 15. Cell 2 holds 50, with children 60 and 15, so it swaps with 15. Cell 1 holds 30, with children 20 and 10, so it swaps with 10.
Cell 0 holds 40, with children 10 and 15, so it swaps with 10, and then sinks once more, past 20. The result, 10, 20, 15, 40, 30, 60, 50, is a heap after only four swaps.
Step by step: Build a heap from a list with heapify. The animated player loads in your browser.
Exercise · Find the bug: Heapify from the wrong end. This heapify sifts down every cell that has a child, but on some arrays it leaves a heap that is not valid. Which line is wrong?
def heapify(cells):
n = len(cells)
for start in range(n // 2):
i = start
while True:
child = 2 * i + 1
if child >= n:
break
if child + 1 < n and cells[child + 1] < cells[child]:
child += 1
if cells[child] >= cells[i]:
break
cells[i], cells[child] = cells[child], cells[i]
i = child
return cellsPredict what happens
Q You run heapify on the array 40, 30, 50, 20, 10, 60, 15. Which cell do you sift down first?
Answer: C
Leaves are already heaps, so skip them. The last cell with a child is 7 // 2 - 1 = 2. Sift it down, then cells 1 and 0.
A common job is to find the k largest items of a long stream, or of a list too big to sort. Use a min-heap of size k.
Push each new item. If the heap now holds more than k items, pop. The pop removes the smallest, which cannot be among the k largest. At the end, the heap holds the k largest items, and its top is the weakest of them, the kth largest.
Trace it with k = 3 and the stream 7, 2, 9, 4, 8. After 7, 2 and 9 the heap holds all three, with 2 on top. Then 4 arrives, the heap has four, and the 2 is popped.
Then 8 arrives, and the 4 is popped. The heap holds 7, 8 and 9, and its top, 7, is the third largest.
Each item costs about log k steps, so a list of n items costs O(n log k), and the memory is only k items.
To keep the k largest items of a stream, hold them in a min-heap of size k. Push each item, and pop when the heap is too big.
Step by step: Keep the 3 largest of a stream. The animated player loads in your browser.
Exercise · Predict the output: What does the heap throw away?. A min-heap keeps the 3 best scores of a stream. This code prints each value that it pops. What does it print?
import heapq
best = []
for score in [5, 1, 8, 3, 9, 4, 7]:
heapq.heappush(best, score)
if len(best) > 3:
print(heapq.heappop(best), end=" ")
print()Here is every operation side by side, with two plain arrays as a comparison. The last two rows are the ones that surprise people.
| Operation | Min-heap | Sorted array | Unsorted array | What sets the cost |
|---|---|---|---|---|
| Push an item | O(log n): add at the end, sift up | O(n): later items shift along | O(1): add at the end | The height of the tree |
| Pop the smallest | O(log n): move the last item up, sift down | O(1): keep it largest first, and take from the end | O(n): scan for the smallest | The height of the tree |
| Peek at the smallest | O(1): read cell 0 | O(1) | O(n): scan | Where the smallest is kept |
| Build from n items (heapify) | O(n) | O(n log n): a sort | O(1): nothing to do | Most items move only a short way |
| Search for a value | O(n): a heap has no search order | O(log n) with binary search | O(n) | A heap only orders parent and child |
| Keep the k largest of n items | O(n log k): a heap of size k | O(n log n): sort everything | O(n k): scan k times | The size of the heap |
| Memory for each item | One cell, no pointers | One cell | One cell | The array layout |
A heap is the right tool when you add items and ask for the best one again and again. It is the wrong tool when you need to look up an arbitrary value.
Now drive the heap yourself. Type a value and push it, pop the top, or peek. Each operation runs step by step, and the heap is drawn twice: as a tree, and as the array that holds it. The step counter shows the cost: a comparison or a swap each count as one step.
Try these six, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a MinHeap class with an array called cells. You write five methods: push, pop, peek, size and to_list.
Three things to take care over:
push adds the value at the end, then sifts it up. Stop when the value is not smaller than its parent, so an equal parent stays where it is.pop returns -1 on an empty heap. Otherwise it moves the last value to cell 0, shortens the array, and sifts down toward the smaller child. When both children are equal, take the left one.to_list shows your array. The tie rules are fixed, so your cells must match the expected ones exactly.Each test creates a new, empty heap, calls your methods in order and compares every value they return. 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 when items arrive over time and you keep asking for the most urgent one: the next task to run, the nearest driver, the cheapest offer. Pushing and popping cost log n, and the best item is always one step away.
It is also the right tool for "the k best of a very long list", because a heap of size k needs only k items of memory.
Choose a hash map when you ask "is this value here?": a heap cannot answer that without scanning. Choose a sorted array or a search tree when you need every item in order, or the item right above a given value. A heap only promises the top.
Reading the array from left to right does not give sorted values. Only cell 0 is guaranteed. The array [10, 20, 15] is a valid heap, and 20 comes before 15. To get sorted values, pop one at a time.
print(heap.cells) # [10, 20, 15]: not sortedA heap is not sorted. Only the top is promised to be the smallest, so reading the array from left to right does not give sorted values.
Many libraries give a heap with the smallest on top, and some give the largest on top. Check which one you have. To keep the k largest, you need a min-heap of size k, because the item you throw away is the smallest. In languages without a max-heap, store negative values.
heapq.heappush(best, score) # a min-heap: pop drops the smallest
heapq.heappush(best, -score) # a max-heap in disguise: pop drops the largestDuring a pop, swap with the smaller child, not with either one. If you swap with the larger child, the smaller one ends up below it, and the order rule breaks.
child = 2 * i + 1
if child + 1 < n and cells[child + 1] < cells[child]:
child += 1 # without this line, the left child is always usedThe formulas (i - 1) // 2, 2i + 1 and 2i + 2 are for an array that starts at index 0. If you start at index 1, as many books do, the parent is i // 2, and the children are 2i and 2i + 1. Pick one, and use it everywhere.
parent = (i - 1) // 2 # for an array that starts at 0
parent = i // 2 # for an array that starts at 1: do not mix the twoA heap has no search order. Looking for a value means scanning every cell, which costs O(n). If you need to find or remove arbitrary items, pair the heap with a hash map, or use a different structure.
42 in heap.cells # scans every cell: O(n)(i - 1) // 2, and the children are 2i + 1 and 2i + 2.Explain 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 idea and the shape
Q1/2 A hospital triage desk always sends in the most urgent patient, whoever arrived first. Which structure behaves like this?
Answer: C
A priority queue hands out the most urgent item whatever the arrival order. A heap is the usual way to build one, and a sorted array is slower to add to.
Q2/2 What are the two rules of a min-heap?
Answer: B
The shape rule makes the tree complete, so it fits an array. The order rule only compares each parent with its children, which keeps the smallest on top. A left-smaller, right-larger rule belongs to a search tree.
Checkpoint · The array layout
Q A heap is stored in an array that starts at index 0. Where is the parent of the item at index 6?
Answer: B
The parent of index i is (i - 1) // 2. For i = 6 that is 5 // 2 = 2. Index 6 is the right child of index 2, since 2 * 2 + 2 = 6.
Checkpoint · Push and pop
Q1/3 A min-heap holds 10, 20, 15. You push 12. After the sift-up, what does the array hold?
Answer: C
12 goes to index 3. Its parent is index 1, holding 20, and 12 is smaller, so they swap. Then its parent is 10, which is smaller, so it stops.
Q2/3 You pop from a min-heap that holds 10, 20, 15, 30. What moves to the top first, before the sift-down?
Answer: C
A pop moves the last item to index 0, so the tree stays complete. The 30 is then sifted down: it swaps with the smaller child, 15.
Q3/3 Why does a pop sift down toward the smaller child?
Answer: B
If the item swapped with the larger child, the smaller child would end up below it, and a child would be smaller than its parent.
Checkpoint · Building and top k
Q1/2 What does heapify do, and what does it cost to turn n items into a heap?
Answer: C
Heapify starts at the last item that has a child and sifts down, then moves back one cell at a time. Most items are near the bottom and move only a step or two, so the total is O(n).
Q2/2 You want the 3 largest scores of a long stream. Which heap do you keep?
Answer: C
The smallest of the three best is the one you throw away when a better score arrives, so it must be on top. That is a min-heap of size 3.
Checkpoint · Choosing a heap
Q1/2 You need to know whether the value 42 is in a heap of n items. What does it cost?
Answer: C
A heap only orders a parent against its children. A value can be anywhere below a larger one, so a search can look at every cell.
Q2/2 A product page needs its 10 cheapest offers out of 100,000. Which approach costs the least memory and time?
Answer: C
The heap of size 10 costs about log 10 per price and holds only 10 prices. Sorting costs n log n, and a heap of everything holds all 100,000 prices.
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.