AlgoViz

Two heaps

medium 22 min

The two heaps pattern keeps a max-heap for the smaller half of the values and a min-heap for the larger half.

A MedianFinder with the two heaps pattern

Read it, run it, change a line and run it again.

Loading editor…

low is a max-heap built on heapq by storing negated values. add routes by value and moves at most one root; median reads only the roots. An empty finder raises a clear error instead of an IndexError.