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.