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.

Input: operations as add,num or find_median separated by semicolons. Output median results with 1 decimal place.

Example

Input
add,1;add,2;find_median;add,3;find_median
Output
1.5
2.0
Reasoning
  • Initially, two numbers are added to the data structure: 1 and 2.
  • When find_median is called, the median of the current data stream [1, 2] is calculated as the average of the two middle numbers, which is 1+22=1.5\frac{1+2}{2} = 1.5.
  • Then, the number 3 is added to the data stream, making it [1, 2, 3].
  • When find_median is called again, the median of the current data stream [1, 2, 3] is the middle number, which is 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.