CodingNodes / Heap / Priority Queue / Find Median From Data Stream System design Space play · ←→ step · R restart

Problem

Design a class MedianFinder that receives numbers one at a time and can report the median of everything received so far.

  • MedianFinder() creates an empty finder.
  • addNum(num) adds the integer num to the stream.
  • findMedian() returns the median as a double: the middle number if the count is odd, or the average of the two middle numbers if it is even.

Constraints

  • −10^5 ≤ num ≤ 10^5
  • findMedian is only called after at least one addNum
  • At most 50 000 calls in total

Examples: pick one to animate

Solutions

TimeO(log n) add, O(1) median SpaceO(n)

Time: addNum does a constant number of heap pushes and pops, each costing O(log n). findMedian only reads the two roots.

Space: Every number added is stored once, in one of the two heaps.

Sorting after every insert would be slow, but we only need the middle. Split the numbers into a smaller half and a bigger half. Keep the smaller half in a max-heap lo (its root is the largest of the small numbers) and the bigger half in a min-heap hi (its root is the smallest of the big numbers). Keep the halves balanced, with lo allowed one extra number. Then the median is lo's root, or the average of the two roots. One helper handles both heaps (a flag picks the order). The heaps are arrays the code manages itself, drawn here as array and tree.