Skip to content

Running Median

HardHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class MedianFinder that takes numbers one at a time and can report the median of everything added so far.

  • add_num(num) (addNum in TypeScript) adds an integer.
  • find_median() (findMedian) returns the median: the middle value if the count is odd, or the average of the two middle values if it is even.
m = MedianFinder()
m.add_num(1)
m.add_num(2)
m.find_median()   →  1.5
m.add_num(3)
m.find_median()   →  2

Both methods should be fast; sorting on every call is too slow.

Constraints

  • -10^5 <= num <= 10^5
  • At most 5 * 10^4 calls are made in total.
  • find_median is only called after at least one number has been added.