📘
Find Median from Data Stream
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_medianis called, the median of the current data stream [1, 2] is calculated as the average of the two middle numbers, which is 21+2=1.5. - Then, the number 3 is added to the data stream, making it [1, 2, 3].
- When
find_medianis called again, the median of the current data stream [1, 2, 3] is the middle number, which is 2.0.
Constraints:
- -10^5 <= num <= 10^5
- At least one add before any median call
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.