Heaps: always know the smallest
- Say what a heap costs (the smallest in O(1), a push or a pop in O(log n), heapify in O(n)) and why its list isn't sorted, with measurements against scanning and sorting
- Draw a heap as a tree stored in a list, write sift up and sift down with the parent and child index arithmetic, and answer how a heap works in layers
- Use heapq with tuple priorities, a count that ends every tie and negation for a max-heap, and pick min, nsmallest or sorted by the size of k
- Keep the k best in a heap of size k, merge sorted streams, and always take what's due soonest, with ties at one timestamp settled on purpose
- Delete lazily by checking each entry as it reaches the top, and spend credits soonest expiry first while replaying calls in time order
- Answer the follow-ups: a sorted list or a balanced tree, quickselect, two heaps for a running median, and Dijkstra as a search that pops the nearest node
A GPU credit ledger with expiring credits
OpenAI candidates report this question from phone screens and onsites, more often than any other OpenAI coding question but one (7 reports). It starts with a statement like this one, and only its first level:
Build a ledger for GPU credits. Timestamps and amounts are integers. Calls can arrive in any timestamp order: a grant or a spend recorded now can land before a balance you already read, and the balance must reflect it.
grant(credit_id, amount, start)addsamountcredits that count from timestarton.spend(amount, timestamp)uses credits attimestamp.balance(timestamp)returns what's left at that time: every grant withstart <= timestamp, minus every spend at or beforetimestamp.A repeated
credit_id, or an amount that isn't positive, raisesValueErrorand changes nothing.
Call Returns grant("A", 10, 0)grant("B", 5, 3)spend(4, 2)balance(2)6balance(3)11spend(3, 1)balance(2)3grant("A", 7, 5)raises ValueError
spend(3, 1) comes in after the balances were read, and it still happened at time 1. So the balance at 2 drops from 6 to 3.
Level 1 is a sum. Level 2 makes credits expire: a credit can pay while start <= t < expires, and each spend draws from the usable credit that expires soonest. Level 3 adds overdraft: once a spend needs more than there is, every balance from then on is None, and a grant recorded later can clear it.
You don't write it yet. First you build a heap, the structure that always knows which credit expires soonest, and learn to replay calls in time order. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.
A heap is a cheaper cousin of sorting: it keeps only the smallest item in its place, which costs far less than sorting everything again after each change. Heaps come back all through the coding builds, where small systems grow in levels: the cache's expiry sweep, the billboard rotation and the work queue's leases each keep a heap of deadlines.
A heap always knows the smallest item
Some questions keep asking one thing of a collection that keeps changing: which item is the smallest right now? The credit that expires soonest. The meeting that ends first. The farthest of the points you've kept. The nearest server you haven't reached yet.
A heap answers that question quickly. This lesson builds one from a plain list, uses it in three patterns, and ends back at the GPU credit ledger.
Look at the smallest in O(1), push or pop in O(log n)
Here's what a heap promises, with n the number of items it holds:
- Look at the smallest: O(1). It's always
heap[0]. - Push an item, or pop the smallest: O(log n).
- Turn a list of n items into a heap: O(n).
Test that against the two things you'd try first: scan for the smallest each time, or keep the list sorted. Each step below pops the smallest item and pushes a new one, on a list of n random floats.
# unsorted list: find the smallest every time
def scan(a, new):
for x in new:
a.remove(min(a))
a.append(x)
# sorted list, sorted again after each push
def sort_every_time(a, new):
for x in new:
a.pop(0)
a.append(x)
a.sort()
# sorted list, each new item inserted in place
def keep_sorted(a, new):
for x in new:
a.pop(0)
bisect.insort(a, x)
# a heap, with heapq
def heap(a, new):
for x in new:
heapq.heappop(a)
heapq.heappush(a, x)
One pop and one push on a heap of 1,000 took 0.17 µs. About how long on a heap of 100,000?
Only heap[0] has a known place, and the rest of the list isn't sorted
heapify turns a list into a heap, but it doesn't sort it. Watch what it does to seven numbers.
import heapq
h = [30, 12, 45, 7, 21, 18, 60]
heapq.heapify(h)
print(h)
print(h[:4])
print(heapq.nsmallest(4, h))
[7, 12, 18, 30, 21, 45, 60]
[7, 12, 18, 30]
[7, 12, 18, 21]
h[0] is the smallest. The rest isn't sorted: 30 sits before 21. So h[:4] is not the four smallest, and heapq.nsmallest is.
A heap keeps exactly one item in a known place. The second smallest is at index 1 or 2. Nothing past that is promised.
In the editor, h is the heap that heapify made. Write first_k(h, k): its k smallest items, smallest first, and leave h as it was.
The tree lives in a plain list
A heap is a tree, but it has no node objects. The tree is the list, read by index.
The children of index i sit at 2i + 1 and 2i + 2
In the list [7, 12, 18, 30, 21, 45, 60], index i has its children at 2i + 1 and 2i + 2. What are the children of 12, at index 1?
Push: add at the end, then swap up while smaller than the parent
With the tree stored in a list, a push is a short loop. Put the new item at the end of the list. Then, while it's smaller than its parent at (i - 1) // 2, swap the two and move up to the parent's index. Stop at the root, or as soon as the item isn't smaller. Push 10 onto h and print it:
h = [7, 12, 18, 30, 21, 45, 60]
push(h, 10)
print(h)
push(h, 10) on [7, 12, 18, 30, 21, 45, 60]. At which index does 10 end up?
Pop: move the last item to the top, then swap it down with its smaller child until neither is smaller
A pop takes the top item, and then has to fill the hole it leaves.
def pop(heap):
last = heap.pop()
if not heap:
# it was the only item
return last
top, heap[0] = heap[0], last
sift_down(heap, 0)
return top
You can't just delete index 0, because that leaves a hole at the top. So take the root, and move the last item into its place. Then push that item down: while one of its children is smaller, swap it with the smaller child. That's called sifting down, and you write the sift_down this code calls.
Here's a pop from the list the push left. 30 is green as it moves down, and its children are orange.
1. 30 moved to index 0 2. swapped with 10 3. swapped with 12 30 swaps with the smaller child each time. At index 3 its children would sit at 7 and 8, past the end, so it stops.
It has to be the smaller child. That child moves up and becomes the parent of the other one. In row 1 of the figure, swapping 30 with 18 instead would put 18 above 10.
A pop compares twice per level: once to find the smaller child, and once against the item. Sedgewick and Wayne's algorithms booksite gives the bound: at most 1 + lg n compares for a push, and at most 2 lg n for a pop, where lg n is . They state it for a max-heap, and it's the same for a min-heap.
These two functions, with the sift_down you're about to write, matched heapq pop for pop over 20,000 random pushes and pops.
In the editor, sift_down(heap, i) has its loop and its swap already. Fill in the middle, which sets smallest to the index of the smallest of the item and its children.
Finish sift_down(heap, i). The item at index i may be bigger than its children. Swap it with its smaller child, and repeat until neither child is smaller or it has no children. The children of i are at 2 * i + 1 and 2 * i + 2, and either one can be past the end of the list. Set smallest to the index whose item should sit at i.
Heapify builds a heap in O(n), sifting down from the bottom up
Pushing n items one at a time costs O(n log n) in the worst case. A list you already have can become a heap faster. Every leaf is already a heap of one item. So sift down every parent, from the last parent back to the root. The last parent is index n // 2 - 1.
def heapify(a):
for i in reversed(range(len(a) // 2)):
sift_down(a, i)
Here it is on the list from the start of the lesson. Each row is the list after one sift down:
start after [2] after [1] after [0] 45 swaps with 18, then 12 with 7, then 30 sinks past 7 and 12. Green cells moved in that step.
The last row is the same list heapq.heapify gave.
Why is that linear? Look at where the items sit. Half of them are leaves and never move. A quarter sit one level up and can sink one level at most. An eighth can sink two levels at most, and so on. The long walks belong to the few items near the top.
15 items in 4 levels. At most how many swaps can heapify need, sifting down from the bottom up?
Count the compares with a class whose __lt__ adds one
Python's < calls an object's __lt__ method, and heapq compares two items with <. So to count compares, use a class whose __lt__ adds one to a counter. On 100,000 random floats:
| Way to get there | Comparisons | Per item |
|---|---|---|
heapq.heapify | 165,000 | 1.65 |
heappush one at a time, random order | 227,419 | 2.27 |
heappush one at a time, largest first | 1,468,946 | 14.69 |
sorted() | 1,529,071 | 15.29 |
heappop all 100,000 from a heap | 1,534,823 | 15.35 |
is about 16.6. In random order most pushes stop near the bottom, so pushing is cheap on average. Largest first is the worst case: every new item is the smallest so far, and it climbs all the way to the root.
Popping everything is a sort, called heapsort, and it costs what a sort costs. On a million random floats, heapifying a copy took 25.7 ms, a million pushes 46.7 ms, and sorted() 137.1 ms.
In the editor, Counted wraps a number, and Counted.compares is one counter that every Counted shares. by_heapify and by_pushes are the two ways to build a heap. Write __lt__ so each < adds one, then count_compares(build, values), which counts the compares one build makes.
Erik Demaine's lecture on priority queues and binary heaps from MIT's 6.006, the array-as-tree layout and heap sort among them. About 51 minutes, so save it for after the lesson.
heapq: a min-heap on a list you own
heapq does the same moves in C, on a plain list you own. Six things cover nearly every use:
heapq.heappush(h, item)andheapq.heappop(h): O(log n). Popping an empty heap raisesIndexError.h[0]: the smallest, without removing it. O(1).heapq.heapify(h): turns a list into a heap in place. O(n).heapq.heappushpop(h, item)pushes, then pops.heapq.heapreplace(h, item)pops, then pushes. Each does one sift instead of two, andheapreplacekeeps the size fixed, which suits a heap of size k. A pop and a push in the right order give the same result, so these two names are not worth memorizing.
It's a min-heap: heappop always returns the smallest.
Put a count after the priority, so a tie never compares the items
A heap compares items with <. Tuples compare field by field, so a (priority, thing) pair is ordered by its priority first. That's how you attach a priority to anything. But watch what a tie does:
h = [(30, {"id": "promo"})]
heapq.heappush(h, (30, {"id": "refund"}))
TypeError: '<' not supported between instances of 'dict' and 'dict'
Both priorities are 30, so the comparison moves on to the dicts, and dicts can't be compared with <. The error comes when the heap first compares those two entries. That can be the push, or a later push or pop.
The heapq docs name this problem, and their fix is a count in the middle. Here's how the two comparisons run:
| Field compared | No count | A count in the middle |
|---|---|---|
| 1. the priority | 30 == 30: a tie, go on | 30 == 30: a tie, go on |
| 2. the next field | dict < dict: TypeError | 0 < 1: decided here, and the dicts are never compared |
Counts are never equal, so every tie ends at the count. Counts also go up, so equal priorities come out in the order they went in:
import itertools
jobs = [(2, {"name": "resize"}), (1, {"name": "bill"}), (2, {"name": "email"})]
h, count = [], itertools.count()
for priority, job in jobs:
heapq.heappush(h, (priority, next(count), job))
print([heapq.heappop(h)[2]["name"] for _ in range(3)])
['bill', 'resize', 'email']
itertools.count() hands out 0, 1, 2 and so on. Any number that goes up works just as well, such as an int you add 1 to.
In the editor, run_order(jobs) takes jobs as dicts with a "name" and a "priority", and its last line pops them all. Write the one push inside the loop, with the count in the middle.
Stand math.inf in for a missing priority
A priority that's missing, like None for credit that never expires, can't be compared with a number at all:
h = [(30, "promo")]
heapq.heappush(h, (None, "base"))
TypeError: '<' not supported between instances of 'NoneType' and 'int'
Put a value in its place that sorts where you want it. math.inf is larger than every number, so credit that never expires sorts last.
In the editor, soonest_first(credits) takes credits as dicts with an "id" and an "expires" that can be None. Write the one push, with math.inf in place of None, so the credits come back soonest expiry first.
Each credit is a dict with an "id" and an "expires" time. The time is an int, or None for credit that never expires. Write the one push in soonest_first(credits). The heap must hand the credits back soonest expiry first, never-expiring credit last, and credits that expire at the same time in the order they were given. The last line reads each credit from the end of its heap entry.
For a max-heap of numbers on Python 3.12, push the negative
In Python 3.12, every public heapq function works on a min-heap. For numbers, push the negative, and negate again on the way out:
scores = {"ana": 91, "bo": 78, "cy": 95, "di": 88}
h = [(-score, name) for name, score in scores.items()]
heapq.heapify(h)
neg, name = heapq.heappop(h)
print((-neg, name))
Scores ana 91, bo 78, cy 95, di 88 go in as (-score, name). What comes out of the first pop, negated back?
Keep the k best in a heap of size k
The first pattern. Out of n items, you want the k best: the k closest points to the origin, the k largest files, the k most recent events. There are three ways:
- Sort everything and take k: O(n log n) time and O(n) memory.
- Heapify a copy and pop k times: O(n + k log n) time, and O(n) memory for the copy.
- Keep a heap of only k items, the best so far, and let each new item replace the worst of them if it beats it: O(n log k) time and O(k) memory. This one also works on a stream you can't hold.
The top of a size-k heap is the item a newcomer has to beat
A min-heap of size 3 keeps the 3 largest of the stream 5, 1, 8, 3, 9. After 9 arrives, what's on top: the value a newcomer has to beat?
For the k smallest, negate, so the largest kept item is on top
The k smallest run the other way. The window sits at the low end, and its weakest member is the largest value kept. That's the one a newcomer replaces, so it has to be on top. That's a max-heap, built by negating:
def k_smallest(values, k):
# negated: the largest kept value on top
heap = []
for x in values:
if len(heap) < k:
heapq.heappush(heap, -x)
# x is smaller than the largest kept
elif -x > heap[0]:
heapq.heapreplace(heap, -x)
return sorted(-x for x in heap)
print(k_smallest([5, 1, 8, 3, 9, 2, 7, 4], 3))
[1, 2, 3]
heapq.nsmallest and heapq.nlargest do this for you, and most items cost them one comparison.
The squared distance orders points the same way the distance does, and it skips a square root per point.
In the editor, KClosest keeps the k points closest to the origin while points arrive one at a time, and closest() reads them out. Write add(point), with the farthest kept point on top of self.heap.
Finish add(point) in KClosest. Points arrive one at a time. self.heap keeps the k points closest to the origin so far, and never holds more than k entries. Compare by squared distance, x * x + y * y. Store entries as (-squared distance, point), so the farthest kept point is on top.
Use min for one, nsmallest for a few, and sorted once k is a large share of the input
Four ways to get the k smallest, timed on a million random floats:
On a million floats, which is fastest for the single smallest, k = 1?
Merge sorted streams with one heap entry per stream
The second pattern. You have k sources, and each is already sorted: log files from k servers ordered by time, k sorted runs of a big sort, k rows of a sorted table. You want one sorted stream.
The heap holds each stream's front, and the smallest front goes out next
Only the front of each source can be next. So a heap holds one entry per source: its current front, and an iterator that hands out the rest of that source. Pop the smallest front, hand it out, and push the next item from the same source. merge_sorted in the editor does this. Here it is on four streams:
print(merge_sorted([[1, 4, 9], [2, 3, 10], [5, 6], []]))
Merge the streams [1, 4, 9], [2, 3, 10], [5, 6] and []. At most how many entries sit in the heap at once?
The merge wins on streams and on the first few items, not on a full merge in memory
The bug in merge_sorted was a tie. Two fronts with equal values made Python compare the next field, two iterators, and iterators can't be compared. The fix puts the stream number in the middle, (value, i, it), so i settles every tie, as the count did in the job queue.
heapq.merge is the library version, and its docs say it doesn't pull the data into memory all at once. It takes each stream as its own argument, so a list of streams goes in as heapq.merge(*streams): the * unpacks the list, and heapq.merge(*[a, b]) is heapq.merge(a, b).
When everything already fits in memory, the merge isn't faster. On 100 sorted lists of 10,000 integers each:
100 sorted lists of 10,000 integers. Which is faster for the full merge: sorted(chain(...)) or heapq.merge?
Always take what's due soonest
The third pattern, and the one the practice problem runs on. Key the heap by when each thing is due: a deadline, an expiry, an end time. Then heap[0] is always the next thing to deal with. Here it's rooms and meetings.
The question: given meetings as (start, end) pairs, each holding a room for start <= t < end, how many rooms do you need? The obvious answer keeps a list of rooms, each with the time it's next free. Each meeting, in start order, takes the first room that's free:
def rooms_by_scan(meetings):
# when each room is next free
rooms = []
for start, end in sorted(meetings):
for i, free_at in enumerate(rooms):
if free_at <= start:
rooms[i] = end
break
else:
rooms.append(end)
return len(rooms)
meetings = [(9, 10), (9, 11), (10, 11), (10, 12), (11, 13), (12, 14)]
print(rooms_by_scan(meetings))
Six meetings: 9 to 10, 9 to 11, 10 to 11, 10 to 12, 11 to 13 and 12 to 14. How many rooms do they need?
Only the room that frees up soonest matters, so keep the end times in a heap
The scan is correct, and it checks every room for every meeting: O(n × r) for n meetings and r rooms. But you never need to know which room is free. You only need to know whether the one that frees up soonest is. So keep the end times of the rooms in use in a heap, ends:
- Take the meetings in start order.
- Pop every end time at or before the meeting's start. Those rooms are free again.
- Push the meeting's own end.
The most end times the heap ever holds at once is the answer. Here's that on the same six meetings:
| Meeting | Popped, ended by its start | ends after the push | Rooms in use |
|---|---|---|---|
| 9 to 10 | [10] | 1 | |
| 9 to 11 | [10, 11] | 2 | |
| 10 to 11 | 10 | [11, 11] | 2 |
| 10 to 12 | [11, 11, 12] | 3 | |
| 11 to 13 | 11, 11 | [12, 13] | 2 |
| 12 to 14 | 12 | [13, 14] | 2 |
Three rooms, at 10. The third row is the tie rule doing its job. The meeting that ends at 10 gives its room to the one that starts at 10, because 10 <= 10. On the line of hours, those two bars meet but don't overlap.
On 100,000 random meetings, starting anywhere from 0 to 100,000 and lasting up to 200 or up to 2,000, the two answers agreed. The heap version took 48.4 ms when they needed 135 rooms, and 54.5 ms when they needed 1,141. The scan took 111.9 ms and 941.2 ms. Its cost grows with the rooms, and the heap's barely does.
In the editor, write the loop of rooms_needed(meetings): take the meetings in start order, pop every end time in ends at or before the start, push the meeting's end, and keep the most rooms in use in most.
Write the loop in rooms_needed(meetings). meetings is a list of (start, end) pairs in any order. Each meeting holds a room for start <= t < end, so a room freed at 10 can host a meeting that starts at 10. Keep the end times of the rooms in use in the heap ends. Return the most rooms in use at once.
Calls that arrive out of order have to be replayed in time order
The room loop's first rule says start order, and the loop has to sort for it. Meetings arrive in the order they were booked, but the loop must see them in the order they happen. Feed them in as given, and [(5, 9), (1, 3), (2, 6)] needs 3 rooms instead of 2. The meeting from 5 to 9 went in first, so it's counted as holding a room at 1 and at 2, before it starts.
The practice problem's calls arrive out of order too, and there it changes who pays. Here are two credits of 10 each, and two spends. The spend at time 4 is recorded first, and the spend at time 2 after it:
| Credit | Usable |
|---|---|
| A, 10 | from 0 until 20 |
| B, 10 | from 3, and never expires |
The spends are 5 at time 2, recorded second, and 10 at time 4, recorded first.
A and B hold 10 each. A spend of 10 at time 4 is recorded before a spend of 5 at time 2. Applied as they arrive, how much is left unpaid?
Sort the events you know up front, and use a heap when one event creates others
Sort or heap for the replay? If every event is known when the replay starts, sort them once: O(n log n), done in C. A heap earns its place when handling one event creates others, like a job that finishes and frees a machine for the next one. The heapq docs describe that use: a scheduler whose heap holds all the incoming events, with the smallest scheduled time coming off first.
The practice problem uses both:
- The spends are all known, so they're sorted.
- The credits are a heap keyed by expiry. Which credit pays depends on which ones have started and what's left of each, and that changes at every step of the replay.
In the editor, write finish_time(durations, machines): jobs run in the order given, each on the machine that frees up soonest. The heap free holds the time each machine is next free, and the answer is when the last job ends.
Greg Hogg puts tuples on a heap: it orders them by the first item and breaks ties with the second.
Delete lazily: leave a dead entry until it reaches the top
A heap gives you the smallest and nothing else. To remove any other item, you first have to find it, which is a scan through the list. Then you have to repair the heap.
Removing from the middle costs O(n), but skipping a dead entry at the top costs one pop
Here are two ways to delete 1,000 items from a heap of 100,000 random (value, id) pairs, and then pop the 1,000 smallest of what remains:
# eager: find it, remove it, rebuild
for v in victims:
h.remove(v)
heapq.heapify(h)
# lazy: leave it, skip it when it comes off
removed, out = set(victims), []
while len(out) < 1000:
x = heapq.heappop(h)
if x not in removed:
out.append(x)
The eager version took 4,931 ms, and the lazy one 4.8 ms. Both include the 3.8 ms first heapify.
That's lazy deletion: leave a dead entry in the heap, and check every entry as it comes off. The heapq docs give the reason: removing an entry or changing its priority would break the heap invariant.
Three things are exact here:
- A dead entry stays in the list, and counts in
len(heap), until a pop removes it from the top. - It costs one pop, O(log n), when it gets there.
- Whatever reads the top checks it first. That means every pop, and a look at
heap[0]too.
There are three common ways to tell a live entry from a dead one:
- A mark on the entry. The
heapqdocs' recipe replaces a removed task with a placeholder, and skips the placeholder on pop. - A check against the truth. The entry says one thing, a dict says another, and only a match counts. A cache can key its heap by
(expires_at, count, key), and treat a popped entry as real only if the key is still stored with that sameexpires_at. - A condition you can see at the top. A heap keyed by expiry brings expired entries to the top first. You drop them as you meet them, and never search for one.
The practice problem is the third kind.
In the editor, heap holds (expires, name) entries, and the set removed marks the dead ones, the first kind above. Write pop_live(heap, removed): pop past the dead entries and return the first live one.
A credit heap keyed by expiry drops each expired credit when it reaches the top
The practice problem's credits sit in a heap keyed by expiry. Tuples can't be changed, so entries that change are lists: [expires, count, credit_id, left].
When a spend looks at the top and finds a credit that has expired, it drops it and looks again, at O(log n) per drop. A credit that's partly used stays on top with less left. That's safe, because the amount left isn't part of the key.
Here a spend of 60 at time 12 meets three credits. Each row is one look at the top:
| Top | Expires, left | What happens | Still to pay |
|---|---|---|---|
| trial | 10, 20 | expired, since 10 <= 12: pop it | 60 |
| promo | 30, 50 | pays 50, stays on top | 10 |
| promo | 30, 0 | nothing left: pop it | 10 |
| base | never, 100 | pays 10, stays on top with 90 | 0 |
A credit used up exactly can stay in the heap with 0 left, until the next spend reaches it. That's lazy deletion again. Anything that adds up the balance has to skip it, or simply add its 0. Popping it the moment it hits 0 works just as well.
In the editor, write spend(heap, amount, now), the spend from the table. Look at the top credit again and again: drop it if it has expired or is empty, and otherwise take what it can pay. Return the part nothing could pay.
Write spend(heap, amount, now). The heap holds [expires, count, credit_id, left] lists, soonest expiry first, with math.inf for credit that never expires. A credit can pay while now < expires. While there's still an amount to pay and credit in the heap, look at the top credit. Drop it if it has expired or has nothing left. Otherwise take what you can from it, and leave it in place with less left. Return the part of amount nothing could cover, or 0 when it's all paid.
To change a key, push a new entry or index the heap, never write it in place
Sometimes an entry's key changes after it is in the heap, such as a credit whose expiry moves earlier. Changing it in place looks harmless.
h = [[10, "trial"], [30, "promo"], [45, "refund"], [60, "bonus"]]
heapq.heapify(h)
h[3][0] = 5
print([heapq.heappop(h)[1] for _ in range(4)])
bonus sat at the bottom, due at 60. You write its expiry as 5 in place, and pop all four. Which comes out first?
A worked example: the k-th smallest in a sorted matrix
The problem: an n by n matrix of integers in which every row and every column is sorted ascending. Given k from 1 to n², return the k-th smallest value, counting repeats. It's worth working because it has two good answers, and the real question is which one to use when.
Clarify, then give the plain answer
Here n is 4 and k is 6:
M = [[2, 6, 9, 14],
[3, 8, 12, 17],
[7, 10, 15, 20],
[11, 13, 18, 25]]
print(sorted(v for row in M for v in row)[:6])
[2, 3, 6, 7, 8, 9]
The sixth smallest is 9.
Clarify. Repeats count separately, so in [[1, 1], [1, 2]] the third smallest is 1. k counts from 1. Values are integers, which matters for the second method.
Give the plain answer. Flatten and sort: O(n² log n) time and O(n²) memory. Say it and its cost, then do better.
The rows are sorted streams, so merge them and stop at the k-th
That's the merge pattern. A heap holds each row's front. Popping k times hands out the values in order, and the k-th pop is the answer. You don't need the pops, only the k-th value, so look at heap[0] after k - 1 of them:
def kth_by_heap(matrix, k):
# each row's smallest
heap = [(row[0], r, 0) for r, row in enumerate(matrix)]
heapq.heapify(heap)
for _ in range(k - 1):
value, r, c = heap[0]
if c + 1 < len(matrix[r]):
heapq.heapreplace(heap, (matrix[r][c + 1], r, c + 1))
else:
heapq.heappop(heap)
return heap[0][0]
print(kth_by_heap(M, 6))
9
Each pop takes one row's front and pushes the next value from that row:
| Step | Pops | From row | Pushes | Heap values after |
|---|---|---|---|---|
| 1 | 2 | 0 | 6 | 3, 6, 7, 11 |
| 2 | 3 | 1 | 8 | 6, 7, 8, 11 |
| 3 | 6 | 0 | 9 | 7, 8, 9, 11 |
| 4 | 7 | 2 | 10 | 8, 9, 10, 11 |
| 5 | 8 | 1 | 12 | 9, 10, 11, 12 |
After those five pops, the heap holds one front per row, and the popped values sit to their left:
M Blue values are popped: 2, 3, 6, 7, 8. Orange values are in the heap, one front per row, with 9 on top.
heap[0] holds 9. The cost is O(n + k log n) time and O(n) memory. The column sorting goes unused.
In the editor, M is the matrix above. Write smallest_k(matrix, k): merge its rows with a heap of (value, row, column) fronts, and return the k smallest values in order.
The second answer counts: how many entries are at most x?
The second answer never merges. It picks a value x, counts the entries at most x, and binary-searches x until the count reaches k. The count comes first, and it takes O(n) with a staircase walk from the bottom-left corner:
- If the cell is at most x, so is everything above it in that column, since columns are sorted. Add those cells, and step right.
- Otherwise, step up.
print(count_at_most(M, 9))
How many values in M are at most 9?
Binary-search the value, not a position
This is the binary search from the sorting and binary search lesson, with one change: lo and hi are values, not indexes into a list. The question at each middle value is "are at least k entries at most mid?"
The two bounds keep two promises:
- Every value below
lohas fewer than k entries at most it, so the answer is at leastlo. It starts atM[0][0], the smallest value, where nothing is below. hihas at least k entries at most it, so the answer is at mosthi. It starts atM[-1][-1], the largest value, which has all n² entries at most it.
Each round counts at mid = (lo + hi) // 2. At least k means mid might be the answer, so hi = mid keeps it. Fewer than k means the answer is above mid, so lo = mid + 1 drops it. Either way the range shrinks, and the loop stops when lo == hi. Both promises still hold, so that one value is the smallest x with at least k entries at most x: the k-th smallest.
print([kth_by_search(M, k) for k in (1, 6, 16)])
[2, 9, 25]
Here are the rounds for k = 6:
| lo | hi | mid | Entries at most mid | Next |
|---|---|---|---|---|
| 2 | 25 | 13 | 10 | at least 6, so hi = 13 |
| 2 | 13 | 7 | 4 | fewer than 6, so lo = 8 |
| 8 | 13 | 10 | 7 | hi = 10 |
| 8 | 10 | 9 | 6 | hi = 9 |
| 8 | 9 | 8 | 5 | lo = 9 |
lo and hi meet at 9. That value is always in the matrix. If it weren't, x - 1 would have the same count, and x wouldn't be the smallest. The cost is O(n log(hi - lo)) time and O(1) memory, and it doesn't depend on k.
Here's where the integer clarification counts: mid = (lo + hi) // 2 needs integers. With floats, search over the matrix's distinct values instead, or use the heap.
In the editor, count_at_most is the staircase walk you wrote. Write kth_by_search(matrix, k): the loop with the two promises, returning the value where lo and hi meet.
Test the edges, then pick: the heap for small k, the binary search for large k
Test the edges. k = 1 returns M[0][0], and k = n² returns M[-1][-1]. Repeats are where an off-by-one hides, so check both methods against sorting. On 500 random matrices up to 6 by 6, with values from 0 to 29 and full of repeats, both agreed with sorting for every k.
Measure. On a 1,000 by 1,000 matrix with values below , which is about 30 rounds of the binary search:
| k | Heap | Binary search | Sort everything |
|---|---|---|---|
| 10 | 0.09 ms | 2.4 ms | 85 ms |
| 1,000 | 0.38 ms | 2.0 ms | 82 ms |
| 500,000 | 202.34 ms | 3.6 ms | 88 ms |
Answer the real question. The heap costs O(n + k log n) and wins when k is small. The binary search costs O(n) per round for about 30 rounds, whatever k is. At k = 500,000, the heap is slower than sorting all million values. Say that tradeoff before they ask for it.
In the editor, write first_disagreement(kth, matrix), a tester for any k-th smallest function kth(matrix, k). Three functions are there to test it on: by_sort sorts every value and is right, skips_repeats drops repeated values, and last_one_wrong is wrong only at the last k.
What interviewers ask next
A heap, a sorted list or a balanced tree?
- A heap gives the smallest in O(1), and push and pop in O(log n). Nothing else: no search, no removal from the middle, no order beyond the root.
- A sorted list gives min, max and any rank by index, and binary search. But each insert costs O(n): 23.55 µs for a pop from the front and an insert at 100,000 items, in the race at the start of the lesson.
- A balanced binary search tree, such as a red-black tree, gives O(log n) insert, delete of any item, min and max, and walks in order. Python's standard library has none.
Take the tree when you need to delete arbitrary items, find the next item above a value, or walk a range in order.
The sorting and binary search lesson built the two bisect searches. On a sorted list a, bisect.bisect_left(a, x) returns the first index whose item is at least x, and bisect.bisect_right(a, x) the first index whose item is greater than x.
In the editor, values is a sorted list. Write next_above(values, x): the smallest item greater than x, found with bisect. A heap can't answer that question.
Only one k-th item, once? Quickselect, O(n) on average when the values are distinct
Quicksort picks a pivot, moves the smaller items to its left and the rest to its right, then sorts each side. Quickselect does the same split around a random pivot, then keeps only the side that holds position k. The booksite frames the median as a special case of this: selection, finding the k-th smallest of a set of numbers.
import random
# k-th smallest, k counted from 0
def quickselect(items, k):
items = list(items)
lo, hi = 0, len(items) - 1
rng = random.Random(0)
while True:
if lo == hi:
return items[lo]
p = rng.randint(lo, hi)
items[p], items[hi] = items[hi], items[p]
pivot, store = items[hi], lo
# smaller than the pivot to the left
for i in range(lo, hi):
if items[i] < pivot:
items[i], items[store] = items[store], items[i]
store += 1
items[store], items[hi] = items[hi], items[store]
if k == store:
return items[k]
if k < store:
hi = store - 1
else:
lo = store + 1
print(quickselect([30, 12, 45, 7, 21, 18, 60], 3))
21
It's O(n) on average on distinct values, because each round keeps one side and the sides shrink geometrically. It's O(n²) in the worst case, which a random pivot makes unlikely.
Repeats break that. An item equal to the pivot never goes left. On 8,000 equal values, each round shrinks the range by one, and the median took 24 million comparisons, four times as many as on 4,000. That's quadratic whatever the pivot. With many repeats, split into less, equal and greater, and stop when k lands in the equal block.
For the median of a million random floats, this plain Python took about 150 ms on a typical input (70 to 205 ms over 20 inputs). That's no faster than sorted(d)[k] at about 140 ms, because the sort runs in C. heapq.nsmallest(k + 1, d)[-1] took 984 ms. A heap of size k is the wrong tool when k is half of n.
In the editor, write select(items, k): quickselect with a three-way split into less, equal and greater, so a list full of repeats can't make it quadratic.
A running median: two heaps, each holding half the numbers
Numbers arrive one at a time, and after each one you need the median. Keep two heaps:
low, a max-heap by negation, holds the smaller half.high, a min-heap, holds the larger half.
Each new number goes to low if it's no bigger than low's top, and to high otherwise. Then one top moves across if it has to, so that low holds as many as high, or one more. The median is low's top, or the mean of the two tops.
low stores each number negated, the max-heap trick for numbers, and high stores them as they are. RunningMedian in the editor follows these rules. Here are its medians on a stream of six:
rm, medians = RunningMedian(), []
for x in [5, 15, 1, 3, 8, 7]:
rm.add(x)
medians.append(rm.median())
print(medians)
Add 5, 15, 1, 3, 8 and 7, one at a time. What's the median after all six?
The median across many machines: binary-search the value
Don't ship the data. Each machine sorts its own numbers once. Then binary-search the value, the way kth_by_search did in the worked example: lo and hi are values, and each round asks whether at least k numbers are at most mid.
- Send a candidate x to every machine.
- Each machine answers how many of its numbers are at most x. On a sorted list that's
bisect.bisect_right(a, x), the first index whose item is greater thanx. - The sums say which half to keep: at least k, and
hi = mid. Fewer, andlo = mid + 1.
Integer values below take about 32 rounds, each with one small message per machine.
The mode is a counting question instead. Send each value to the machine that owns its hash, so all copies of a value meet in one place. Count there with a Counter from the hash-maps lesson, and compare each machine's top count.
In the editor, each machine holds a sorted list of numbers. Write kth_across(machines, k): binary-search the value, and let each machine count its numbers at most mid with bisect.bisect_right.
Dijkstra's algorithm pops the nearest node, and is correct only when no edge is negative
Breadth-first search explores a graph in rings: every node one step from the start, then every node two steps away, and so on, taken from a first-in, first-out queue. That finds the fewest steps when every step costs the same. When edges have different costs, say network delays, swap its queue for a heap of (distance so far, node). Then always settle the nearest unsettled node next.
A node can be pushed more than once, with different distances. So skip an entry for a node already settled. That's lazy deletion again.
links = [("a", "b", 4), ("a", "c", 1), ("c", "b", 2),
("b", "d", 5), ("c", "d", 8), ("d", "e", 3)]
print(delays(links, "a"))
Links a to b 4, a to c 1, c to b 2, b to d 5, c to d 8, d to e 3. What's the shortest delay from a to e?
Back to the GPU credit ledger
Before you write the ledger, list the tests you'd write for any heap code:
- Ties at equal priority, with items that can't be compared.
- An empty heap:
heappopraisesIndexError. - One item, and all items equal.
- The boundary: a credit that expires at exactly now.
- Input in descending order, the worst case for pushes.
- A check against
sorted()on random input.
Here are level 1's rules again, from the statement at the start of the lesson:
grant(credit_id, amount, start)addsamountcredits that count from timestarton.spend(amount, timestamp)uses credits attimestamp.balance(timestamp)returns every grant withstart <= timestamp, minus every spend at or beforetimestamp.- Calls arrive in any timestamp order. A spend recorded late still counts at its own timestamp.
- A repeated
credit_id, or an amount that isn't positive, raisesValueErrorand changes nothing.
In the editor, write level 1. CreditLedger records each grant in self.grants and each spend in self.spends, and balance(t) works the answer out from them only when it's asked for.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.A heap holds n items. What does it cost to look at the smallest, to pop it, and to push a new item?
2.After
heapq.heapify(h),his[7, 12, 18, 30, 21, 45, 60]. Which gives the four smallest items?3.You push
(expires, credit)onto a heap, where each credit is a dict, and two credits expire at 30. What happens?4.To keep the 3 closest points, you push
(dist, point)onto a heap and pop whenever it holds 4. Which 3 points does it keep?5.Each meeting holds a room for start <= t < end. Before placing a meeting that starts at
start, which line frees the rooms that are done?6.Your heap of
[expires, count, credit_id, left]entries holds a credit that was cancelled. What should you do?
Practice
Sources (12)
- heapq: Heap queue algorithm · Python 3.12 documentation · Oct 26, 2026
“Heaps are binary trees for which every parent node has a value less than or equal to any of its children.”
- heapq: heapify · Python 3.12 documentation · Oct 26, 2026
“Transform list x into a heap, in-place, in linear time.”
- heapq: Priority Queue Implementation Notes · Python 3.12 documentation · Oct 26, 2026
“Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order.”
- heapq: nsmallest · Python 3.12 documentation · Oct 26, 2026
“The latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function.”
- heapq: merge · Python 3.12 documentation · Oct 26, 2026
“does not pull the data into memory all at once”
- heapq: Heap queue algorithm · Python 3.14 documentation · Nov 10, 2026
“The API for max-heaps is named using a _max suffix.”
- bisect: insort_left · Python 3.12 documentation · Oct 26, 2026
“Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.”
- Sorting Techniques · Python 3.12 documentation · Oct 26, 2026
“The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.”
- queue: A synchronized queue class · Python 3.12 documentation · Oct 26, 2026
“With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first.”
- 2.4 Priority Queues · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Apr 24, 2022
“the heap algorithms require no more than 1 + lg n compares for insert and no more than 2 lg n compares for remove the maximum.”
- 2.5 Sorting Applications · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Mar 18, 2018
“Finding the median is a special case of selection: finding the kth smallest of a set of numbers.”
- 4.4 Shortest Paths · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jan 10, 2025
“Dijkstra's algorithm solves the single-source shortest-paths problem in edge-weighted digraphs with nonnegative weights using extra space proportional to V and time proportional to E log V (in the worst case).”