v9.1.1
Menu

Find Median from Data Stream

hardFREEHeap / Priority QueueBlind 75

Design a data structure that supports adding integers and finding the median efficiently.

Implement a class MedianFinder with:

  • add_num(num): add the integer num to the stream.
  • find_median(): return the median of all numbers added so far as a number (not a string). With an even count, the median is the mean of the two middle values.

Input: operations as add,num or find_median separated by semicolons. The test harness parses them, calls your methods, and prints each median result with 1 decimal place.

Example

Input
add,1;add,2;find_median;add,3;find_median
Output
1.5
2.0
Reasoning
  • The input is a sequence of operations read left to right: add,1 and add,2 put 1 and 2 into the stream, find_median asks for the median of everything added so far, then add,3 grows the stream before the second query.
  • The median is the middle value once the numbers are in sorted order. At the first query the stream holds {1,2}\{1, 2\}, an even count, so there are two middle values and the median is their mean: 1+22=1.5\frac{1+2}{2} = 1.5.
  • At the second query the stream holds {1,2,3}\{1, 2, 3\}, an odd count, so the single middle value (the 2nd of 3) is the median: 22, shown with one decimal place as 2.0.
  • The output has one line per find_median query, in order: 1.5 then 2.0. An earlier answer is never revised when later numbers arrive.
  • Notice that insertion order is irrelevant: adding 3, 1, 2 gives the same sorted stream 1,2,31, 2, 3 and the same median, 2.02.0.

Constraints

  • -10^5 <= num <= 10^5
  • At least one add before any median call

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.