Four problems where items change or leave a heap. The move: never search the heap, but record why an entry is stale, and discard it when it reaches the top.
You work on a ride dispatcher, a leaderboard, a support desk and a latency monitor. In each one, items enter a heap, and then the world changes. A request is cancelled, a score changes, a ticket is reset, or a request leaves the window.
A heap is good at one thing: the best entry is on top. It cannot find an entry in the middle. This street is about what to do instead.
| Problem | What makes an entry stale | How you know |
|---|---|---|
| Heap with removal by id | the request was cancelled | its id is not in the set of waiting ids |
| Top scorers with updates | the score has changed | the entry's score differs from the creator's score |
| Task manager with priority changes | the ticket was reset | its key differs from the ticket's current key |
| Kth largest in a sliding window | the request left the window | its position is marked gone |
The method is the same in every row. Leave the stale entry where it is, and test it when it reaches the top. This is called lazy deletion, because the deletion happens later.
Exercise · Predict the output: The leader, and the heap size. Three creators start at 0 points. Each update pushes a fresh entry, and the code throws away entries on top whose score is out of date. What does it print: the leader after each update, then the size of the heap?
import heapq
scores = [0, 0, 0]
heap = [(0, 0), (0, 1), (0, 2)]
heapq.heapify(heap)
leaders = []
for who, points in [[0, 5], [1, 7], [0, 3], [1, -4], [2, 9]]:
scores[who] += points
heapq.heappush(heap, (-scores[who], who))
while -heap[0][0] != scores[heap[0][1]]:
heapq.heappop(heap)
leaders.append(heap[0][1])
print(*leaders, len(heap))Before you write code, answer one question: how will I know that an entry is out of date when I see it? The answer is a test that costs O(1), such as a set lookup or a comparison with the current value.
Every live item has at least one entry in the heap. An entry whose item is gone, or whose key is older than the item's current key, is stale. Before you read the top, a loop discards stale entries until the top is live.
The cost is the reason to accept the extra entries. Cancelling each of 100,000 requests by scanning the heap would cost up to 5,000,050,000 comparisons in total. With lazy deletion, a run of 100,000 random actions made 50,017 pushes and 45,376 pops, because each entry is pushed once and popped at most once.
Leave the stale entry in place, and discard stale entries with a loop when they reach the top.
Exercise · Find the bug: Two stale entries on top. Requests arrive with an urgency, can be cancelled, and are served from the highest urgency, the smaller id on a tie. Serving returns -1 when nothing is waiting. Which line is wrong?
import heapq
def serve_order(ops):
heap = []
waiting = set()
served = []
for kind, ident, urgency in ops:
if kind == 1:
heapq.heappush(heap, (-urgency, ident))
waiting.add(ident)
elif kind == 2:
waiting.discard(ident)
else:
if heap and heap[0][1] not in waiting:
heapq.heappop(heap)
if heap:
waiting.discard(heap[0][1])
served.append(heapq.heappop(heap)[1])
else:
served.append(-1)
return servedThe Academy lessons Heaps and priority queues and Two heaps and running medians show a heap that only grows, and one value removal in a median. This street changes three things.
A changed key is a fresh entry. In the leaderboard, each update pushes a new entry with the new score. The older entries stay in the heap, and each one is stale when its score differs from the creator's current score.
With the updates in the prediction, the heap held 8 entries at the end, and only 3 were current. That is fine: stale entries leave when they surface.
A key can grow with time. In the ticket problem, urgency is the value plus the rate times the seconds waited. Store the key as value minus rate times the time the growth started. Every waiting ticket gains the same amount at any moment, so the order of the keys never changes.
Take a rate of 2, ticket 1 with the value 10 at second 0, and ticket 2 with the value 14 at second 5. At second 8 their urgencies are 26 and 20, so ticket 1 is served. A heap keyed on the value alone would serve ticket 2.
Equal keys need a tie field. In the window problem, two requests can have the same latency. Give each a unique key, such as the latency times a large number plus the position. Then a request marked gone cannot be confused with an equal one.
Take the requests 5, 2, 8, 1, 9, 3 and 7, with a window of 4 and k = 2. The second slowest of each window is 5, 8, 8 and 7.
A cancel for a request that has not arrived does nothing. Track waiting ids, not cancelled ids.
Exercise · Break it: The cancel that comes first. This serves requests by highest urgency, and a cancel removes a request. It keeps a set of cancelled ids and skips them on top of the heap. Find an input where it gives a wrong answer.
import heapq
def serve_order(ops):
heap = []
cancelled = set()
served = []
for kind, ident, urgency in ops:
if kind == 1:
heapq.heappush(heap, (-urgency, ident))
elif kind == 2:
cancelled.add(ident)
else:
while heap and heap[0][1] in cancelled:
heapq.heappop(heap)
served.append(heapq.heappop(heap)[1] if heap else -1)
return servedSolve them in this order. The first marks stale entries with a set. The second compares scores, the third rewrites the key, and the fourth uses two heaps with gone marks.
Before you code each problem, write two lines: how you will know an entry is stale, and what the key is. If the first line needs a search, rethink it.
Give each problem about 25 minutes. Spend the first five on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases.
Four cases come back on every rung. They are a cancel for an item that never arrived, a cancel of an item already served, an empty heap after the cleanup, and equal keys. Write one small test for each.
When a solution fails, print the heap after each step. A wrong answer almost always means a stale entry was served, or a live entry was discarded.
Checkpoint · Custom heaps and lazy deletion
Q1/5 A request in the middle of a heap is cancelled. What is the standard way to handle it?
Answer: B
Searching a heap costs O(n). Marking costs O(1), and each entry is discarded at most once, when it reaches the top.
Q2/5 Why must the cleanup of stale entries be a loop?
Answer: B
A single check removes one stale entry. If the next entry is stale too, the code would use it as the answer.
Q3/5 A creator's score changes from 8 to 3. What does the leaderboard do?
Answer: B
The old entry stays in the heap. It is recognised as stale because its score no longer matches the creator's current score.
Q4/5 Urgency grows by a fixed rate each second. Which key keeps the heap order unchanged as time passes?
Answer: B
Every waiting ticket gains the same amount at any moment, so subtracting the growth makes the keys fixed. The order of the keys is the order of the urgencies.
Q5/5 Two requests have the same latency, and one has left the window. Why give each entry a unique key?
Answer: B
With the latency alone, a gone mark could hit the wrong request. A key such as latency times a large number plus the position names exactly one request.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.