Lesson 18 of 40Trees and graphs
Heaps
Use a heap to grab the smallest or largest item in O(log n), and solve top k, k-way merge and scheduling problems.
A job scheduler always runs the most urgent task next. A game server matches the two closest-ranked players. A maps app expands the nearest unexplored road first. Each of these needs the same thing over and over: give me the smallest (or largest) item, fast, while new items keep arriving.
Sorting the whole list every time costs O(n log n) per request. A heap answers in O(log n), and it is the data structure behind priority queues in every language.
A tree that lives in an array
A min-heap is a binary tree with one rule: every parent is smaller than or equal to its children. So the smallest item is always the root. (A max-heap flips the rule, and the largest is at the root.)
Unlike a BST, a heap says nothing about left versus right. It only orders parents above children. That looser rule is what makes it cheap to maintain.
A heap is also a complete binary tree: every level is full except possibly the last, which fills from the left. Because there are no gaps, you can store it in a plain array, level by level, with no pointers at all. For the item at index i:
| Relative | Index |
|---|---|
| left child | 2 * i + 1 |
| right child | 2 * i + 2 |
| parent | (i - 1) // 2 |
Here is the same min-heap two ways. Node 3 is at index 1, so its children are at indexes 3 and 4.
Index 0 holds the root, the smallest value: 1.
Push: sift up
To add an item, put it at the end of the array (the next free spot in the bottom level). It may be smaller than its parent, which breaks the rule. So swap it upward until its parent is smaller. This is sift up.
To remove the smallest item, take the root. Move the last item into the root's place, then swap it down with its smaller child until both children are bigger. This is sift down.
Push 5 into an empty heap. It is the root.
A complete tree with n items has about log₂ n levels, and each sift moves one level per swap. So push and pop are O(log n), and peeking at the minimum is O(1) (it is just index 0).
Heapify: O(n), not O(n log n)
To turn an existing list into a heap, you could push items one by one: O(n log n). Heapify does better. Sift down every non-leaf node, starting from the last one and moving toward the root.
Why is that O(n)? Half the nodes are leaves and need no work. A quarter are one level up and sift at most one step. An eighth sift at most two steps. Most nodes are near the bottom, where sifting is cheap, and the total adds up to less than 2n swaps. Python's heapq.heapify does exactly this.
Heaps in Python and TypeScript
Python ships heapq: plain functions that treat a list as a min-heap. Before Python 3.14 there was no max-heap at all, so the standard trick is to negate values on the way in and out. (The 3.14 additions are covered further down.)
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.What does this print?
import heapq h = [] for x in [4, 1, 7, 3]: heapq.heappush(h, -x) print(-heapq.heappop(h), -heapq.heappop(h))
The top k pattern
"Find the k largest numbers" in a stream of a million. Sorting is O(n log n) and needs all the data at once. Instead, keep a min-heap of size k holding the k largest seen so far. Its root is the smallest of those k, the one most likely to be kicked out.
For each new number: push it, and if the heap grows past k, pop the smallest. At the end, the heap holds the k largest and the root is the k-th largest.
Press Run (⌘ Enter) to see what happens.Each step costs O(log k), so the whole thing is O(n log k) time and O(k) space. With k = 10 and n = 1,000,000, that is far cheaper than sorting, and it works on a stream you can only read once.
The counterintuitive part trips people up: for the k largest, you use a min-heap. For the k smallest (or k closest points), use a max-heap of size k.
Two heaps: the running median
To report the median of a stream after every number, split the numbers into two halves. A max-heap holds the smaller half (its root is the largest of the small numbers) and a min-heap holds the larger half. Keep their sizes within one of each other. The median is the root of the bigger heap, or the average of both roots when they are the same size. Each new number costs O(log n). This is the median-finder practice problem.
K-way merge: one candidate per list
You have k sorted lists (log files from k servers, k sorted shards of a database query) and need one sorted stream. Comparing the heads of all k lists at every step costs O(k) per item. A heap holds one candidate per list, the smallest item that list has not output yet, so the next item overall is always the heap's root.
Pop the root, output it, and push the next item from the same list. The heap never holds more than k entries, so each item costs O(log k), and merging N items in total costs O(N log k). Each heap entry carries where it came from, (value, list_index, position), so you know which list to refill from.
Start with the head of each list. The root, 1, is the smallest item anywhere, because every list is sorted.
Press Run (⌘ Enter) to see what happens.The index i in each tuple does two jobs: it says which list to refill from, and it breaks ties when two values are equal, so Python never has to compare the third items. For linked lists, the same idea is Merge k Sorted Lists, which Linked List Techniques covers along with the divide-and-conquer alternative.
Kth Smallest Element in a Sorted Matrix is a k-way merge in disguise: each row is a sorted list. Start with the first item of each row, pop k − 1 times, and the root is the answer. That is O(k log n) for an n × n matrix. The alternative interviewers like to hear is binary search on the answer value (see Binary Search): count the items <= mid with a staircase walk from a corner in O(n), giving O(n log(max − min)). The heap is simpler to get right; the binary search wins when k is close to n².
In Python, heapq.merge(*iterables) does a lazy k-way merge for you and is the right call at work, for example when merging sorted files too large to load at once (the merge step of an external sort).
Task Scheduler: a heap plus a cooldown queue
You have CPU tasks labelled by letter, and the same letter must wait at least n time units before it runs again. Each unit you can run one task or sit idle. What is the minimum total time?
The greedy rule: at every time unit, run the available task with the most copies left. Running the most frequent task first keeps the idle gaps small, because it is the task that would otherwise pile up at the end with nothing to fill the gaps between its copies. So keep a max-heap of remaining counts for tasks that are ready, and a queue of tasks cooling down, each with the time it becomes ready again. The queue stays in time order on its own, because tasks enter it in the order they run.
Press Run (⌘ Enter) to see what happens.The simulation is O(T log 26) for T time units, which is effectively linear. The formula is O(n) to count and worth knowing because interviewers often ask for it next. Lay out the most frequent task, with top copies, as top − 1 full frames of length n + 1, plus a last partial frame holding every task that ties for the top count. That is (top − 1) · (n + 1) + ties. If there are so many other tasks that the frames overflow, no idle time is needed at all and the answer is just len(tasks). Take the max of the two. The random test at the end checks the simulation and the formula against each other, which is exactly how you would gain confidence in a formula you derived under pressure.
What does this print?
from collections import Counter
tasks, n = list("AAABBBCCDE"), 2
counts = Counter(tasks).values()
top = max(counts)
ties = sum(1 for c in counts if c == top)
print(max(len(tasks), (top - 1) * (n + 1) + ties))Tie-breakers: never let Python compare the payload
heapq compares tuples item by item. If two entries tie on priority, Python moves on to compare the second items. When those are dicts, objects or anything without <, you get a TypeError, usually only in production, on the first day two jobs share a priority.
Press Run (⌘ Enter) to see what happens.The fix is a monotonic counter in the middle: (priority, count, item). Counts are unique, so the comparison never reaches the item. It has a second benefit: equal-priority entries come out in insertion order (first in, first out), which a heap does not guarantee by itself because heaps are not stable. Most job queues want that fairness. To break ties differently, put the rule in the tuple: (priority, -created_at, count, item) gives newest first among equals.
The other option is a small class with __lt__ (or @dataclass(order=True) with the payload marked field(compare=False)). That is cleaner when the ordering rule is complicated, but each comparison calls Python code, so tuples are faster in hot loops.
Lazy deletion: removing from the middle
A heap is fast at the root and slow everywhere else. Removing an arbitrary item means finding it (O(n)) and then repairing the heap. Problems like Sliding Window Median need exactly that: as the window moves, the outgoing number must leave one of the two heaps.
The standard trick is lazy deletion. Do not remove the item now. Record that it is pending removal, and drop it later, when it reaches the root and you would otherwise return it. Use a Counter, not a set, because the same value can be in the heap several times and only some copies may be deleted. Keep your own size too, since len(heap) now includes dead entries.
Press Run (⌘ Enter) to see what happens.Every pushed item is popped at most once, live or dead, so the cleanup is amortised O(log n) per operation. The cost is memory: dead entries sit in the heap until they surface. If deletions far outnumber pops, rebuild the heap from the live items now and then. You have met the same idea twice already in other lessons: Dijkstra skips stale entries whose distance is out of date (Shortest Paths), and Max Stack keeps a stack and a heap in sync with a removed set of ids (Design Problems). When items have unique ids, mark ids; when values repeat, count values, as here.
set of values instead of a Counter. The heap holds 4, 4, 9 and you remove one 4. What goes wrong?Max-heaps in Python 3.14
For years the only way to get a max-heap from heapq was the negation trick above. Python 3.14 added public max-heap functions: heapify_max, heappush_max, heappop_max, heappushpop_max and heapreplace_max. They work on a plain list arranged with the largest item at index 0.
Press Run (⌘ Enter) to see what happens.Know both. Many interview platforms and company servers still run Python versions older than 3.14, and the negation trick works everywhere. It also has a limit: you can only negate numbers. For a max-heap of strings or tuples with mixed directions, either use the 3.14 functions or wrap items in a class whose __lt__ is reversed. In an interview, say which version you are assuming before you call heappush_max.
Match the problem to the heap setup.
Common mistakes:
- Using a min-heap for "k smallest" (you need to evict the largest, so use a max-heap).
- Forgetting that
heapqis min-only and negating only on the way in, not on the way out. - Assuming the heap array is sorted. Only
heap[0]is guaranteed;heap[1]is not the second smallest. - Pushing tuples whose second items cannot be compared (two equal priorities with dict payloads raise a
TypeError). Add a counter as a tie-breaker:(priority, count, item).
Kth Largest Element
Given a list of integers nums and a number k, return the kth largest value. This is the kth largest in sorted order, so duplicates count separately.
nums = [3, 2, 1, 5, 6, 4], k = 2 → 5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 → 4Try to beat sorting the whole list.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
K Closest Points to the Origin
Given a list of points points, where each point is [x, y], and a number k, return the k points closest to the origin (0, 0) by straight-line distance. You can return them in any order.
points = [[1, 3], [-2, 2]], k = 1 → [[-2, 2]]
points = [[3, 3], [5, -1], [-2, 4]], k = 2 → [[3, 3], [-2, 4]]Constraints
1 <= k <= points.length <= 10^4-10^4 <= x, y <= 10^4- The tests are chosen so the answer is unique.
Build the structure yourself once. It makes every heap question easier to reason about.
Build a min-heap
Implement a min-heap of numbers stored in a plain array, without using heapq or any library heap.
Methods:
push(x)adds a value (sift it up).pop()removes and returns the smallest value (move the last item to the root, then sift it down). ReturnNone/undefinedwhen the heap is empty.peek()returns the smallest value without removing it (None/undefinedwhen empty).size()returns how many values are stored.
h = MinHeap()
h.push(5); h.push(2); h.push(8)
h.peek() → 2
h.pop() → 2
h.pop() → 5
h.size() → 1For the item at index i, its children are at 2i + 1 and 2i + 2 and its parent is at (i - 1) // 2. push and pop must be O(log n).
- min-heap
- A complete binary tree where every parent is less than or equal to its children, so the minimum is at the root.
- sift up / sift down
- Swap a new item up toward the root, or a moved root down toward the leaves, until the heap rule holds. O(log n).
- heapify
- Build a heap from a list in O(n) by sifting down every non-leaf from the bottom up.
- heapq
- Python's min-heap functions on a list. Negate values for a max-heap.
- top k pattern
- Keep a heap of size k and evict the root when it overflows. O(n log k) time, O(k) space.
- k-way merge
- Merge k sorted sequences by keeping one candidate per sequence in a heap. O(N log k) for N items.
- tie-breaker
- A unique counter in the heap tuple,
(priority, count, item), so equal priorities never compare items and come out first in, first out. - lazy deletion
- Record an item as removed and discard it when it reaches the root, instead of deleting it from the middle.