Sub topic 7
Heaps: always getting the smallest or largest item
This chapter assumes you know Python lists and dictionaries, can read Big-O notation, and have read the earlier chapters on arrays and hash tables. It covers when a heap is the right choice and how to use Python's heapq module.
The problem a heap solves
Some tasks need only one item from a collection: the smallest, the largest, or the most urgent. You need it again and again while new items keep arriving. Examples are a task scheduler, a "top 10 scores" display, and shortest-path search.
You have two obvious options, and both are slow:
- Keep an unsorted list and scan it for the minimum each time. That costs O(n) per query.
- Keep a sorted list. Reading the minimum is cheap, but each insertion shifts elements and costs O(n).
A heap sits between the two. It does not keep everything sorted. It only guarantees that the best item is always easy to reach.
How a heap works
A binary heap is a tree stored in a flat array. In a min-heap, every parent is less than or equal to its children, so the smallest item is at index 0. The children of index i are at 2*i + 1 and 2*i + 2.
- Push adds the item at the end, then moves it up until the rule holds. This costs O(log n).
- Pop removes the root, moves the last item to the root, then moves it down until the rule holds. This costs O(log n).
- Peek reads index 0. This costs O(1).
- Building a heap from n items with
heapifycosts O(n).
Siblings have no order between them. Only the parent-child rule holds, which is why a heap is cheaper to maintain than a sorted list.
Using heapq
Python's heapq module works on an ordinary list and always builds a min-heap.
import heapq
scores = [42, 7, 19, 88, 63, 5]
print(heapq.nlargest(3, scores)) # [88, 63, 42]
heap = []
for s in scores:
heapq.heappush(heap, s)
print(heapq.heappop(heap)) # 5, the smallest itemheapq.nlargest(k, data) returns the top few items without sorting all the data. For small k this is faster than sorted(data)[-k:].
Max-heaps and priorities
heapq has no max-heap. Push negated numbers instead. For tasks with priorities, push tuples. Python compares tuples element by element, so the first element decides the order.
import heapq
tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix outage"))
heapq.heappush(tasks, (3, "clean inbox"))
priority, name = heapq.heappop(tasks)
print(priority, name) # 1 fix outage
largest_first = []
for value in [3, 10, 6]:
heapq.heappush(largest_first, -value)
print(-heapq.heappop(largest_first)) # 10When to choose a heap
| Need | Best fit |
|---|---|
| Repeated "give me the smallest or largest" with inserts | Heap |
| Top k items from a large collection | `heapq.nlargest` or `nsmallest` |
| Membership test or lookup by key | Set or dictionary |
| Sorted iteration, ranges, or the next larger value | Sorted list with `bisect`, or a balanced tree |
| Removing an arbitrary item quickly | Not a heap |
A heap cannot search for an arbitrary value efficiently, because that takes O(n). It also cannot iterate in sorted order without popping every item. If you need either, pick a different structure.
If you only need the minimum once, min(data) is simpler and also O(n). A heap pays off when you query many times while the data changes.
Exercise
A job queue receives thousands of jobs, each with a numeric priority where a lower number is more urgent. Workers repeatedly take the most urgent job while new jobs keep arriving. Which structure fits, and what do the push and pop operations cost?
Show answer
A min-heap, using heapq with (priority, counter, job) tuples. Both heappush and heappop cost O(log n). A sorted list would make each insertion O(n), and an unsorted list would make each pop O(n).
Exercise
You need a max-heap of integers using heapq. How do you get the largest value back?
Show answer
Push the negated values, such as heappush(h, -value). Pop the smallest negated value and negate it again, such as -heappop(h), to get the largest original value.