A heap answers exactly one question: “what is the smallest (or largest) item right now?” It keeps nothing else in order. That’s why it can insert and remove in O(log n).
This post builds on Trees, because a heap is a binary tree with one extra rule, stored inside an array. It leads into Intervals, Greedy and Advanced Graphs. In those topics, “always take the cheapest next thing” almost always has a heap underneath. Dijkstra and Prim’s both do.
How to use this post: Part 1, the method. The checkpoints don’t show answers on the page. Work each one out yourself first, then open the linked chat to have your answer checked.
Heap Properties
Foundation
Think of a company org chart with one rule: every manager is senior to their direct reports. From that rule alone, you can’t tell whether someone in marketing is senior to someone in finance. But you do know for certain that the CEO is the most senior person in the building.
That’s a heap. It’s a partial order, meaning only some pairs are ranked against each other. Enough pairs are ranked to pin down the top, and nothing else.
A min-heap is a binary tree with two properties:
- Order property: every node is less than or equal to its children. So the root is the minimum. (A max-heap flips it: every node is greater than or equal to its children.)
- Shape property: the tree is complete. Every level is full except possibly the last, and the last level fills from left to right with no gaps.
What problem does it solve? You have a collection that keeps changing, and you keep asking for its minimum. A heap answers that without paying to keep the whole collection sorted.
Mechanics
The shape property is what lets a heap live in a plain list. You don’t need node objects or pointers. Number the nodes level by level, left to right, starting at 0. Then the node at index i has these neighbours (0-indexed, which is what Python’s heapq uses):
- left child: 2i + 1
- right child: 2i + 2
- parent: (i - 1) // 2
Why do these formulas work? Because a complete tree has no holes. Level d holds exactly indices 2^d - 1 through 2^(d+1) - 2. And the children of neighbouring nodes sit at neighbouring indices, so nothing gets skipped.
Let’s check it on the worked example:
h = [2, 5, 3, 9, 6, 4, 8]
Index 1 (value 5) has children at 2·1+1 = 3 and 2·1+2 = 4. Those hold 9 and 6. Index 5 (value 4) has its parent at (5-1)//2 = 2, which holds 3. Now check every parent against its children: 2 ≤ 5, 2 ≤ 3, 5 ≤ 9, 5 ≤ 6, 3 ≤ 4, 3 ≤ 8. All of them hold, so it’s a valid min-heap.
Three facts follow from this, and you’ll use them constantly:
- The minimum is h[0]. Start at any node and keep stepping to its parent. The values never go up, and every such path ends at the root.
- The height is floor(log2 n). A complete tree with n nodes has floor(log2 n) + 1 levels. For n = 7 that’s height 2. For n = 8 it’s height 3. Every operation in the next module walks one path from the root to a leaf, so this is where O(log n) comes from.
- The leaves are indices n // 2 through n - 1. Index i has a left child only if 2i + 1 ≤ n - 1, which means i ≤ (n - 2) / 2. For n = 7, indices 0, 1, 2 are internal (they have children) and 3, 4, 5, 6 are leaves. So about half the heap is leaves.
What does the heap not tell you? Anything about siblings or cousins. In h, 5 is drawn on a higher level than 3’s children 4 and 8, yet 5 > 4. So the array is not sorted, and you can’t search a heap. Finding an arbitrary value costs O(n).
Some courses and textbooks (recalled, not derived here) store the heap 1-indexed, with a dummy value at index 0. That changes the formulas to 2i, 2i + 1 and i // 2. It’s the same structure, shifted by one. In Python you’ll use heapq, which is 0-indexed, so the 0-indexed formulas are the ones worth memorising.
Diagram
Implementation
def parent(i):
return (i - 1) // 2 # parent(5) = 2, parent(6) = 2; never called for i = 0
def left(i):
return 2 * i + 1 # left(1) = 3
def right(i):
return 2 * i + 2 # right(1) = 4
def is_min_heap(h):
# Checking each child against its own parent covers every parent-child edge
# exactly once: child indices are 1..len(h)-1, each has exactly one parent.
for i in range(1, len(h)):
if h[parent(i)] > h[i]:
return False
return True
h = [2, 5, 3, 9, 6, 4, 8]
print(is_min_heap(h)) # True
print(is_min_heap([2, 5, 3, 9, 6, 1, 8])) # False: h[5] = 1 < its parent h[2] = 3
print(is_min_heap([]), is_min_heap([7])) # True True (no edges to violate)
print(len(h) // 2) # 3, the first leaf index for n = 7
Complexity: each index formula is O(1). is_min_heap is O(n) time and O(1) extra space, where n = len(h).
Recognition
Problems rarely ask about the heap properties directly. What you’re really checking is whether the problem only ever needs the extreme element, the smallest or the largest. Look for these signs:
- “Repeatedly take the smallest / largest / cheapest / closest / earliest.”
- The collection changes between those questions. Items get added, and the top gets removed.
- You never need, say, the second-largest by rank directly. You never search for a value, and you never walk through the items in sorted order.
When NOT to use a heap:
- You need to find or delete an arbitrary value. A hash set or a balanced BST (from Trees) fits better.
- The data doesn’t change and you read it in order once. Just sort it.
Also, don’t mix up a heap with a BST. A BST orders left < node < right, and that’s what lets you search it. A heap only orders a parent against its children. That supports one thing: “get the top.”
Pitfalls
- Mixing 0-indexed and 1-indexed formulas. With 0-indexing, the parent is (i - 1) // 2, not i // 2. Using i // 2 gives parent(2) = 1, which is wrong, because index 2 is a child of 0.
- Assuming the array is sorted. In general, h[1] is not the second smallest. The second smallest is one of two candidates, h[1] or h[2]. A printed heap won’t look sorted, and that’s correct.
Active Recall
Answer out loud or on paper first.
-
In h = [2, 5, 3, 9, 6, 4, 8], where can the second smallest value live, and where can the third smallest live?
-
Change h[4] from 6 to 1. Which parent-child pairs now violate the order property?
-
Is every sorted array a valid min-heap? Is every valid min-heap sorted?
Mini-task
Included for this module. No problem in this topic’s list asks you to work out the array layout or the index arithmetic from scratch, because they all use heapq. So you’ll practise it here.
You’re given a list that is a valid min-heap of n ≥ 1 numbers. Return its largest value. Getting the right answer is easy. The real question is how few elements you can get away with looking at, and why that’s safe.
Before opening the chat, write down: the observation, the approach, why it’s correct, the complexity.
Transfer test
You’re building a feature where users type a username and you must say whether it’s already taken, among ten million names that change all day. Would you store the names in a heap? Why?
Push and Pop
Foundation
A heap supports two edits, push and pop. Both follow the same plan:
- Make the edit at the end of the array. That’s the one place where adding or removing a slot keeps the tree complete.
- Repair the order property by walking a single path up or down the tree.
Back to the org chart:
- Push is a new employee joining at the bottom. If they’re more senior than their manager, the two swap places. They keep climbing like this until their manager outranks them.
- Pop is the CEO leaving. The person at the very bottom of the chart is put in the CEO’s chair for now. Then they keep swapping with their more senior direct report, until nobody below them outranks them.
Mechanics
An edge here just means a parent-child link. An edge is broken when the parent is bigger than the child.
Push (sift up). Append the new value at index n. That keeps the shape complete. Now only one edge can be broken: the one between the new index and its parent. So while the new value is smaller than its parent, swap the two and move up. This climb is called sift up.
Why is each swap safe? Say the new value x sits at index i, its parent is at p, and h[p] > x. After the swap, x is at p. Its new children are:
- the old h[p], which is > x, and
- h[p]’s other child, which was already ≥ h[p], so it’s also > x.
So the edges below x are fine. Only the edge above x might still be broken. That’s the invariant of the loop, meaning the fact that stays true at every step: at most one edge is broken, and it’s directly above the moving value.
Let’s run it on the worked example h = [2, 5, 3, 9, 6, 4, 8]. Pushing 1 puts it at index 7. It then climbs 7 → 3 → 1 → 0, beating 9, then 5, then 2 (the diagram shows each step). The result is [1, 2, 3, 5, 6, 4, 8, 9]. That took three swaps, which is the height of an 8-node heap (floor(log2 8) = 3).
Pop (sift down). Save h[0], because that’s what you’ll return. Move the last element to index 0 and shrink the list by one. That keeps the shape complete. Now only the edges between the root and its children can be broken. So while the moving value is larger than its smaller child, swap it with that smaller child and move down. This sinking is called sift down.
Why the smaller child specifically? The child you move up becomes the parent of its sibling. If you move up the smaller one, it’s ≤ its sibling, so that new edge is fine. If you move up the larger one, you’ve just made a parent bigger than its child.
Here’s a small case. Take [9, 2, 3]. Swapping 9 with 2 gives [2, 9, 3], which is valid. Swapping 9 with 3 gives [3, 2, 9], and now 3 > 2 breaks the order.
Back to the example. Pop from [1, 2, 3, 5, 6, 4, 8, 9]:
- Save 1.
- Move the last value, 9, to the root.
- 9 sinks 0 → 1 → 3, swapping with the smaller child each time: 2 rather than 3, then 5 rather than 6.
- It stops at index 3, because index 3 is now a leaf (its left child would be at 2·3+1 = 7, and the last index is 6).
Pop returns 1, and the heap is back to exactly the original h. That round trip is a coincidence of this example, not a rule.
Both operations touch only one path from the root to a leaf, so each one is O(log n). Peeking at h[0] is O(1).
Diagram
Implementation
Writing these by hand once is how you stop treating heapq as magic.
def push(heap, val):
heap.append(val) # index len(heap)-1 keeps the tree complete
i = len(heap) - 1
while i > 0:
p = (i - 1) // 2
if heap[p] <= heap[i]: # the only edge that can be broken is p -> i;
break # if it holds, every edge holds
heap[p], heap[i] = heap[i], heap[p]
i = p # push 1 into h: i goes 7 -> 3 -> 1 -> 0
def pop(heap):
if not heap:
raise IndexError("pop from empty heap")
top = heap[0]
last = heap.pop() # removing the last slot keeps the tree complete
if heap: # if the heap had one element, last IS top; nothing to fix
heap[0] = last
i, n = 0, len(heap)
while True:
l, r = 2 * i + 1, 2 * i + 2
smallest = i
if l < n and heap[l] < heap[smallest]:
smallest = l
if r < n and heap[r] < heap[smallest]:
smallest = r
# smallest is now the index of min(heap[i], heap[l], heap[r]) among
# those that exist. Promoting that child keeps it <= its sibling.
if smallest == i: # heap[i] <= both children: order restored
break
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest # pop from [1,2,3,5,6,4,8,9]: i goes 0 -> 1 -> 3
return top
h = [2, 5, 3, 9, 6, 4, 8]
push(h, 1)
print(h) # [1, 2, 3, 5, 6, 4, 8, 9]
print(pop(h), h) # 1 [2, 5, 3, 9, 6, 4, 8]
Both branches of the sift-down comparison have been checked. In the trace, the left child won both times: at index 0 (2 < 3) and at index 1 (5 < 6). For the right-child branch, take [8, 5, 3]. The left child gives 5 < 8, so smallest = 1. Then the right child gives 3 < 5, so smallest = 2. The swap produces [3, 5, 8].
I also ran both functions against heapq on 3,000 random push/pop sequences with duplicates. Every popped value matched.
Complexity: push and pop are O(log n) time and O(1) extra space, where n is the heap size. Peek (heap[0]) is O(1).
The Python you’ll actually write. heapq works on a plain list, and it’s a min-heap only (recalled: the standard library has no max-heap API for general use).
import heapq
h = [2, 5, 3, 9, 6, 4, 8]
heapq.heappush(h, 1)
print(h) # [1, 2, 3, 5, 6, 4, 8, 9] same layout as the hand-written push
print(heapq.heappop(h)) # 1
print(h[0]) # 2, peek without removing
# Max-heap: store negatives. The smallest negative is the largest original.
m = []
for x in [4, 1, 7]:
heapq.heappush(m, -x)
print(-m[0]) # 7
# Priority + payload: tuples compare element by element, so the first field is the key.
t = []
for item in [(2, "b"), (1, "z"), (2, "a")]:
heapq.heappush(t, item)
print([heapq.heappop(t) for _ in range(3)]) # [(1, 'z'), (2, 'a'), (2, 'b')]
# Push-then-pop in one sift (recalled: heappushpop pushes first, heapreplace pops first).
print(heapq.heappushpop([2, 5, 3, 9, 6, 4, 8], 1)) # 1: the new value was already the smallest
print(heapq.heappushpop([2, 5, 3, 9, 6, 4, 8], 7)) # 2: 7 goes in, the old minimum 2 comes out
Recognition
- “Process items in priority order, but new items keep arriving while you process.” A sort can’t handle new arrivals. A heap can.
- “Repeatedly combine or take the two smallest (or largest).” That’s pop, pop, push.
- “The k largest / k smallest / k closest.” Use a heap that never holds more than k items. Here’s the twist: a min-heap of size k keeps the k largest seen so far. Why? Its root is the weakest of the k, so it’s the one to throw out when something better arrives. This flip (a min-heap for the largest) is the single most useful heap idea in interviews. It costs O(n log k) instead of sorting’s O(n log n).
- “Merge several sorted sources.” Keep one candidate from each source in a heap, and pop the smallest.
Here’s where those signals show up in this topic’s list:
- “Keep k”: Kth Largest Element In a Stream, K Closest Points to Origin and Kth Largest Element In An Array.
- “Repeatedly take the largest two”: Last Stone Weight.
- “Merge sorted sources” and “always pick the best available”: Design Twitter and Task Scheduler.
When NOT to use it:
- All items are known up front and you use every one, in order. Sorting once is simpler, and it’s the same O(n log n).
- The priorities are small integers, like counts bounded by n. Bucket sort (Arrays & Hashing) can beat a heap.
- Items expire based on their position in a window. A monotonic deque (Sliding Window) is usually cleaner.
Pitfalls
- Forgetting heapq is a min-heap. If you want the largest but push raw values, you get the smallest. Negate on the way in and again on the way out.
- Negating the wrong field. With tuples, negate only the key: (-dist, x, y), not the whole tuple.
- Tuple ties that fall through to payloads Python can’t compare. When two keys are equal, Python moves on and compares the next field. I checked: pushing (5, Node()) and then (5, Node()) raises TypeError: ‘<’ not supported between instances of ‘Node’ and ‘Node’. The fix is a tie-breaker counter: (5, 0, node), (5, 1, node). This bug depends on the data. Two empty dicts compare equal and don’t crash, but two different dicts do. So it slips past small tests.
- heappop on an empty list raises IndexError. Check
if heap:first. - Calling heappush on a list that isn’t a heap. heapq doesn’t check. It just quietly gives wrong answers.
Active Recall
Answer out loud or on paper first.
-
Push 10 into h = [2, 5, 3, 9, 6, 4, 8]. How many swaps happen, and why?
-
Pop from h = [2, 5, 3, 9, 6, 4, 8] (the original, not the one with 1 pushed). What does it return and what’s the final array?
-
In sift-down, why must the swap go to the smaller child? Give a three-element counterexample.
-
You want the 3 largest values from a stream using a heap that never holds more than 3 items. Min-heap or max-heap, and what do you do when a new value arrives and the heap is full?
Mini-task
Skipped for this module. Design Twitter makes you work out, from scratch, how to merge several sorted sources with a heap. So you’ll practise push and pop properly there, and we’ll cover that reasoning when you solve it.
Transfer test
An emergency room admits patients continuously. Each has a severity from 1 to 5 (5 is most urgent), and among equal severity the earlier arrival goes first. A doctor frees up and asks “who’s next?” several hundred times a day. Would you use a heap? Why?
Heapify
Foundation
Heapify turns any list into a heap, in place. The obvious way is to push the n items one by one, which costs O(n log n). Heapify does it in O(n).
The trick is to fix the tree from the bottom up. A leaf on its own is already a valid one-node heap, so leaves need no work. Start with the lowest nodes that have children, and work toward the root. Each small subtree gets fixed before you touch the subtree above it.
Mechanics
Take the worked example a = [8, 6, 7, 2, 5, 1, 3], so n = 7.
- The leaves (indices n // 2 = 3 through 6) are already heaps. Skip them.
- For i from n // 2 - 1 down to 0, sift a[i] down. This is the same loop pop uses to repair the heap.
Why is it safe to sift down at index i? Sift-down has a precondition, something that must already be true before it runs: both of i’s subtrees must already be valid heaps, so that only a[i] itself can be out of place. Going from right to left, bottom to top, makes sure of that. i’s children have larger indices than i, so their subtrees were fixed earlier in the loop.
Here’s the run (the diagram shows each step):
- i = 2 sinks 7 below 1.
- i = 1 sinks 6 below 2.
- i = 0 sinks 8 two levels, first below 1 and then below 3.
The result is [1, 2, 3, 6, 5, 7, 8], after 4 swaps in total.
Why O(n) and not O(n log n)? Define a node’s height as how many levels it sits above the bottom. A node at height k can sift down at most k steps. Now count how many nodes have each height:
- About half the nodes are leaves. They have height 0, so they do zero work.
- About a quarter have height 1.
- About an eighth have height 2, and so on.
So the total work is n·(0/2 + 1/4 + 2/8 + 3/16 + …). That series adds up to a constant (recalled: the sum of node heights in a complete binary tree is at most n - 1). In other words, the expensive nodes near the root are few, and the many nodes near the bottom are cheap.
Pushing one by one gets this backwards. Each push sifts up, which can take as many steps as the new node is deep. Most of the pushes happen when the heap is already deep, so most of them can be expensive.
I measured it on the worst case for a min-heap, which is input in descending order:
| n | swaps, heapify | swaps, n pushes |
|---|---|---|
| 7 | 4 | 10 |
| 1,000 | 992 | 7,987 |
| 1,000,000 | 999,988 | 17,951,445 |
Heapify stays under n swaps. One-by-one pushes grow like n log n.
Diagram
Implementation
def sift_down(a, i, n):
# Precondition: the subtrees rooted at 2i+1 and 2i+2 are already heaps.
while True:
l, r = 2 * i + 1, 2 * i + 2
s = i
if l < n and a[l] < a[s]:
s = l
if r < n and a[r] < a[s]:
s = r
if s == i:
return
a[i], a[s] = a[s], a[i]
i = s
def heapify(a):
n = len(a)
# Internal nodes are indices 0 .. n//2 - 1 inclusive (0..2 for n = 7).
# Visiting them from n//2 - 1 down to 0 means both children of i (indices > i)
# were already fixed, so sift_down's precondition holds every time.
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
a = [8, 6, 7, 2, 5, 1, 3]
heapify(a)
print(a) # [1, 2, 3, 6, 5, 7, 8]
import heapq
b = [8, 6, 7, 2, 5, 1, 3]
heapq.heapify(b) # in place, returns None
print(b) # [1, 2, 3, 6, 5, 7, 8]
e, s = [], [5]
heapify(e); heapify(s)
print(e, s) # [] [5] (for n = 0 and n = 1 the range is empty: nothing to do)
I checked the hand-written version on 3,000 random lists with duplicates. Every result was a valid heap and a permutation of the input (the same values, rearranged).
Complexity: O(n) time and O(1) extra space, where n = len(a). If you then want the k smallest, that’s k more pops, so O(k log n) more. For a one-liner, heapq.nsmallest(k, a) and heapq.nlargest(k, a) also exist (recalled: they use a bounded heap internally, and they’re best when k is small compared with n).
Recognition
- All the data arrives at once, and then you pop repeatedly, or pop and push in a loop. Heapify first, then do the work.
- You’re about to write a loop of n heappush calls on a list you already have. That’s the O(n log n) way to do an O(n) job.
- “Sort in place with O(1) extra space and O(n log n) in the worst case.” That’s heapify plus repeated extraction (see the mini-task).
When NOT to use it:
- Items arrive over time. There’s nothing to heapify yet, so push them as they come.
- You’re going to pop every single element anyway. Heapify plus n pops is O(n log n), the same as sorting. sorted() is simpler, and faster in practice.
Pitfalls
- Starting at index 0 and going forward. Sifting down at the root first assumes its subtrees are already heaps, but they haven’t been fixed yet. Try it on [8, 6, 7, 2, 5, 1, 3] with i going 0, 1, 2. The root settles on 6 before the 2 and the 1 below it have had a chance to rise. You end with [6, 2, 1, 8, 5, 7, 3], where 6 > 2 at the top. That’s not a heap.
- Using sift-up in the loop instead of sift-down. That puts you back to one-by-one inserts.
- Expecting an exact layout from heapq.heapify. On this example it matches the hand-written version. But CPython’s heapq uses a different sift strategy internally (recalled). On 759 of the 3,000 random lists I tried, the two produced different arrays, and both were valid heaps. So test the heap properties or the order things pop out, never the raw array.
h = heapq.heapify(h). heapify returns None, so you’ve just replaced your list with None.- Heapifying a list you still need in its original order. Heapify works in place, so copy the list first.
Active Recall
Answer out loud or on paper first.
-
For n = 7, why does the loop start at index 2 and not at 6?
-
Before sift_down(a, 0, 7) runs in the trace, what must be true of indices 1 and 2, and what was the array at that moment?
-
heapify is O(n) but n pops afterward is O(n log n). So what does O(n) heapify actually buy you?
-
You heapify with your own code and with heapq.heapify and the arrays differ. Is one of them wrong?
Mini-task
Included for this module. No problem in this topic’s list makes you build a heap bottom-up from scratch. The problems that start from a full array can just call heapq.heapify as a named step. So you’ll practise it here.
Sort a list of numbers in ascending order, in place. Your constraints: O(n log n) time even in the worst case, and O(1) extra space. You may not call sorted(), list.sort(), or any library that sorts for you. Merge sort’s O(n) buffer is off the table too.
Before opening the chat, write down: the observation, the approach, why it’s correct, the complexity.
Transfer test
A job runs once a night over 50 million sensor readings loaded into memory, and needs the 100 lowest readings. Would you use heapify? Why?
Two Heaps
Foundation
One heap gives you one end of the data cheaply. But some problems need a value from the middle. That might be a percentile, a cutoff, or a boundary between “in” and “out” that shifts as data arrives.
Picture two queues of people sorted by height, facing each other across a line on the floor. The short people are on one side and the tall people on the other. To learn anything about the line, you only ever need to look at the two people standing right next to it.
Two Heaps splits the data at that boundary in the same way:
- low is a max-heap of everything below the boundary. Its root is the largest value on the small side.
- high is a min-heap of everything above the boundary. Its root is the smallest value on the big side.
The two roots face each other across the boundary. So whatever you need to know about the boundary is at most two peeks away.
Mechanics
Here’s the worked example. A leaderboard shows the score cutoff for the top quarter of players, and it updates as scores arrive. Let n be how many scores have arrived so far. The top quarter is the best ceil(n/4) scores, and the cutoff is the lowest score still in it. The scores arrive in this order: 40, 10, 90, 70, 20, 60, 80, 30.
Two invariants must hold after every add:
- Order: every value in low ≤ every value in high. You only need to compare the two roots to check this, so it’s the same as max(low) ≤ min(high).
- Size: len(high) = (n + 3) // 4, which is ceil(n/4). When this holds, high is exactly the top quarter, and high[0] is the cutoff.
Why not just keep one min-heap, capped at the size of the top quarter? That works until the quarter grows. At n = 5 the target size jumps from 1 to 2. The new member of the top quarter has to be the best score that was outside it until now. A capped heap has already thrown those scores away. low is where we keep them, arranged so the best of them is on top.
add(x) has two steps.
Step 1, route. If high is non-empty and x > high[0], then x belongs above the boundary, so push it to high. Otherwise push it to low. Either way, the order invariant still holds:
- In the first branch, x > min(high) ≥ max(low). So x is fine in high.
- In the second branch, x ≤ high[0] (or high is empty). So every value in high is still ≥ x.
Step 2, rebalance. While high is too big, pop its minimum and push it to low. While high is too small, pop low’s maximum and push it to high. Either way you’re moving the element that sits right at the boundary, so order is kept. High’s minimum is ≥ everything in low, and low’s maximum is ≤ everything in high.
How many moves can one add trigger? Routing changes len(high) by 0 or 1. The target size also changes by 0 or 1. So at most one move happens per add, and every step is O(log n).
Diagram
Rows 1, 3 and 5 show the three rebalance outcomes:
- Row 1: high is too small, so it fills from low.
- Row 3: high is too big, so it spills into low.
- Row 5: the target size goes up, which pulls the best of the rest (70) across the line.
Implementation
import heapq
class TopQuarterCutoff:
def __init__(self):
self.low = [] # max-heap via negation: every score outside the top quarter
self.high = [] # min-heap: the top quarter; self.high[0] is the cutoff
self.n = 0
def add(self, score):
self.n += 1
# Route. Branch 1: score > self.high[0] >= max(low), so score belongs above.
# Branch 2: score <= self.high[0] (or high is empty), so it can't break
# "every value in high >= every value in low".
if self.high and score > self.high[0]:
heapq.heappush(self.high, score)
else:
heapq.heappush(self.low, -score) # negate: heapq is a min-heap (recalled)
target = (self.n + 3) // 4 # ceil(n/4): n = 1..4 -> 1, n = 5..8 -> 2
# Each loop runs at most once per add (see Mechanics); both keep the order
# invariant because they move the element sitting right at the boundary.
while len(self.high) > target: # e.g. adding 90 at n = 3: 40 spills to low
heapq.heappush(self.low, -heapq.heappop(self.high))
while len(self.high) < target: # e.g. adding 20 at n = 5: 70 moves up
heapq.heappush(self.high, -heapq.heappop(self.low))
def cutoff(self):
return self.high[0] # the smallest score in the top quarter
board = TopQuarterCutoff()
for s in [40, 10, 90, 70, 20, 60, 80, 30]:
board.add(s)
print(s, board.cutoff())
# 40 40 / 10 40 / 90 90 / 70 90 / 20 70 / 60 70 / 80 80 / 30 80
I checked cutoff() after every add against a brute force (sort everything, take the ceil(n/4)-th largest). I ran that on 2,000 random streams with many duplicates, and checked max(low) ≤ min(high) every time. An all-equal stream (five 5s) also works. Ties route to low, and the rebalance pulls them up as needed.
Complexity: add is O(log n) time, because it does a constant number of heap pushes and pops. cutoff is O(1). The structure takes O(n) space, where n is the number of scores added.
To use this for a different boundary, you only change the target formula. Find Median From Data Stream in this topic’s list is built on this same pair of heaps. Working out its size rule and what to return is part of solving it, so I’ll leave that to you.
Recognition
- A running statistic from the middle of the data. “Running” means it has to stay current as data arrives. Think median, a percentile, “the k-th item where k grows with n,” or a cutoff between two groups.
- Two groups of items with a moving boundary between them, where items cross the boundary one at a time.
- A second variant: two heaps with different keys. Items graduate from one heap to the other when some condition becomes true, like a threshold being reached or some time passing. The mini-task below is this variant.
When NOT to use it:
- The data doesn’t change. Sort once and index into it.
- You also need to delete arbitrary items, like in a sliding window over the stream. Plain heaps can’t remove from the middle. You’d need lazy deletion (mark items as deleted, and skip them when they’re popped) or a sorted container.
- k is fixed rather than growing with n. A single bounded heap is enough.
Pitfalls
- Forgetting one of the two negations for low. Push -x, and read -low[0] or -heappop(low). Miss one and low acts as a min-heap, so the boundary quietly breaks.
- Rebalancing by size without routing first, for example always pushing to low. The size rule alone doesn’t keep order. Routing, plus moving only the boundary element, is what keeps it.
- Peeking an empty heap. high[0] on an empty list raises IndexError. Here high is never empty after the first add, because target ≥ 1 for n ≥ 1. Your size rule might allow an empty side, so check.
- Recomputing the answer by sorting each time. That’s O(n log n) per query, and it throws away the whole point of the structure.
Active Recall
Answer out loud or on paper first.
-
After the eight scores in the worked example, add 100 and then 50. What happens at each add, and what’s the cutoff?
-
Why is low a max-heap and high a min-heap, not the other way round?
-
Suppose you skip routing and always push new scores to low, then rebalance by size. Using the example, where does it go wrong?
-
Can an add ever trigger both rebalance loops, or the same loop twice?
Mini-task
Included for this module. Find Median From Data Stream is a labelled example of this pattern, not something you work out from nothing. So no problem in the list makes you come up with the two-heaps idea on your own, and you’ll practise it here.
You start a studio with budget B. There are n possible projects. To start project i, your budget must be at least cost[i]. When you finish it, gain[i] ≥ 0 is added to your budget. The cost is only a threshold, so it isn’t spent. You can complete at most k projects, one at a time. Return the largest budget you can end with.
Example: B = 0, k = 3, projects (cost, gain) = (0, 1), (1, 2), (1, 3), (4, 6), (9, 10). The answer is 10.
Before opening the chat, write down: the observation, the approach, why it’s correct, the complexity.
Transfer test
A monitoring dashboard must show the running 90th-percentile latency of all requests since midnight, updated after every request. A teammate proposes a second requirement: “the 90th percentile over only the last 5 minutes.” Would you use two heaps for each? Why?
Integration
How the four connect.
- Heap Properties give you the invariant (parent ≤ children, complete shape) and the index arithmetic. The other three modules all rest on these.
- Push and Pop are the only two edits. Each one repairs a single path, and that’s where O(log n) comes from.
- Heapify is a bulk push. When all the data is there up front, it runs sift-down from the bottom up and gets O(n).
- Two Heaps combines two heaps. You split the data at a boundary and let the two roots face each other, so the middle becomes as cheap to read as the ends.
Almost every problem in this topic reduces to one of three shapes:
- Repeated extraction: pop the best, maybe push something back, repeat (simulation, scheduling, merging sorted sources).
- Bounded selection: keep only k items in a heap whose root is the one you’d evict (top-k, k closest, k-th largest).
- Split at a boundary: two heaps around a moving middle, or two heaps where items graduate from one to the other.
Distinguishing competing approaches.
| If the problem… | Reach for | Instead of a heap because |
|---|---|---|
| Gives all data up front and you need all of it in order | sort | same O(n log n), simpler |
| Needs one k-th element of a static array, once | quickselect (average O(n)) or heap (O(n log k)) | both are fine; know the trade: quickselect is faster on average, the heap is predictable and works on streams |
| Has priorities that are small bounded integers (counts ≤ n) | buckets | O(n), no log |
| Needs the max/min over a window that slides by position | monotonic deque (Sliding Window) | O(n) total, and expiry is by position, which a heap can’t do without lazy deletion |
| Needs search, arbitrary delete, or ordered iteration | balanced BST / sorted container | a heap only knows its root |
| Needs the extreme repeatedly while items keep arriving | heap | this is its home |
Recognition checklist for an unfamiliar problem.
- Do I repeatedly need the smallest / largest / earliest / cheapest item, and does the collection change between those requests? If both, heap.
- Do I only need k items out of many? Bounded heap of size k, with the root being the one to evict (min-heap for largest-k, max-heap for smallest-k). Cost O(n log k).
- Is the answer a middle value (median, percentile, cutoff) that must stay current? Two heaps facing each other.
- Do items become eligible over time (budget rises, clock advances) and then compete by a different key? Two heaps with different keys, one feeding the other.
- What exactly is the key? Write the tuple before coding: (key, tie-breaker, payload). Negate the key if you need a max.
- Is all the data present up front? heapify instead of n pushes.
- Do I need to delete from the middle, or search? Then a heap alone isn’t enough.
The problems
Work through these with the solving cycle from Part 1. Give each problem a 15-minute honest struggle, then write the key sentence, then review it with spaced repetition.
My cycle note groups heaps with trees. For both, you reconstruct the state on a small example and explain how information flows toward the root.
While you struggle with a heap problem, ask yourself:
- What goes in the heap, and what’s its key?
- What does the root answer? Is it the item I want, or the item I’d throw out?
- Should the heap be bounded at k?
Then simulate the heap’s contents by hand on a small input before you write code.
7 problems · 2 easy · 4 medium · 1 hard · tracker spreadsheet (.xlsx)
| # | Problem | Difficulty | Coach |
|---|---|---|---|
| 1 | Kth Largest Element In a Stream | Easy | ChatGPT · Claude |
| 2 | Last Stone Weight | Easy | ChatGPT · Claude |
| 3 | K Closest Points to Origin | Medium | ChatGPT · Claude |
| 4 | Kth Largest Element In An Array | Medium | ChatGPT · Claude |
| 5 | Task Scheduler | Medium | ChatGPT · Claude |
| 6 | Design Twitter | Medium | ChatGPT · Claude |
| 7 | Find Median From Data Stream | Hard | ChatGPT · Claude |
Take this lesson as a live session
To go through this lesson interactively, with a coach that waits for your answers, open it as a chat.