Running Median of a Stream

hard
Unit 4 · Graphs II0/2 to milestone

Track the median of a stream of numbers as they arrive, such as p50 latency on a live dashboard, without re-sorting everything each time.

The classic solution uses two heaps: a max-heap holding the smaller half and a min-heap holding the larger half, kept balanced so their sizes differ by at most one. The median is then at the top of one or both heaps.

Implement a class RunningMedian:

  • add(x) in O(log⁡n)O(\log n);
  • median() in O(1)O(1): the middle value for an odd count, the average of the two middle values for an even count. Raise ValueError if no numbers have been added.
  • __len__ returns how many numbers have been added.

Python's heapq is a min-heap only; store negated values to simulate a max-heap.

#heaps#streaming#design2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Running Median of a Stream · TechGradify