Loading...
Loading...
Imagine you are processing a continuous stream of integers (e.g., real-time sensor readings, live stock prices). At any point in time, you need to be able to report the median of all integers seen so far — efficiently.
The median is the middle value in a sorted list of numbers. If the list has an even number of elements, the median is the average of the two middle values.
Design a data structure that supports the following two operations:
addNum(num) — Add an integer from the data stream to your data structure.findMedian() — Return the median of all elements inserted so far.You will be given a list of operations and their arguments. Simulate them in order and collect the results of all findMedian calls.
Input:
operations: a list of strings, each either "addNum" or "findMedian"values: a list of lists; for addNum, the inner list contains one integer; for findMedian, the inner list is emptyOutput:
findMedian calls. Each result is a float rounded to 1 decimal place.operations = ["addNum", "addNum", "findMedian", "addNum", "findMedian"]
values = [[1], [2], [], [3], []]
Output: [1.5, 2.0]
Explanation:
operations = ["addNum", "findMedian"]
values = [[42], []]
Output: [42.0]
Explanation: Only one element; median is that element itself.
operations = ["addNum", "addNum", "addNum", "addNum", "findMedian"]
values = [[5], [3], [8], [1], []]
Output: [4.0]
Explanation: Sorted: [1, 3, 5, 8] → median = (3+5)/2 = 4.0
findMedian call works but is O(n log n) per query — too slow for large streams.1 <= total number of operations <= 5 * 10^4 -10^5 <= num <= 10^5 At least one addNum is called before any findMedian At most 5 * 10^4 addNum calls At most 5 * 10^4 findMedian calls
addNum and O(1) per findMedian.findMedian is called before any addNum? (Assume this won't happen per constraints.)