14/30
Part 4 of 7 · Why not a heapLearn and do

A heap can't find a title, so an update pushes a second key

The trouble starts at level 2. To change Harbor's score, you'd remove its old key and add a new one. A heap can't find (-7, 'Harbor') without scanning the whole list, O(n). And deleting from the middle of a heap breaks its order unless you repair it by hand.

The usual way out is a lazy delete. Leave the old key where it is and push a new one. Keep the current score of each title in a dict. When a key reaches the top, check it:

  • If its score isn't the title's current score, it's stale. Drop it and pop again.
  • If its title has already shown in this loop, drop it too.
  • Otherwise, show it.
scores = {"Comet": 9, "Harbor": 7, "Orbit": 5}
heap = [(-9, "Comet"), (-7, "Harbor"), (-5, "Orbit")]
scores["Comet"] = 1
heapq.heappush(heap, (-1, "Comet"))
print(sorted(heap))
[(-9, 'Comet'), (-7, 'Harbor'), (-5, 'Orbit'), (-1, 'Comet')]

Comet has two keys now. The one with 9 will reach the top first, and only the check against scores stops Comet from showing as if it were still the best title.

Each loop of pop_best pops one key, so it always ends: at worst the heap runs out and it returns None.

The editor holds pop_best and a heap with one stale key. Write pop_best(heap, scores, shown) to pop keys until one is current and not yet shown.