Find Median from Data Stream
Design a data structure that supports adding integers from a data stream and querying the median of all values seen so far. Implement addNum(num) to insert a value and findMedian() to return the current median (average of the two middle values when the count is even).
Open official problem prompt ↗Maintain the running median of every number seen so far, answering each median query in constant time no matter how large the stream grows.
Picture a see-saw. The left seat holds the smaller half of the numbers with the biggest of them at the pivot; the right seat holds the larger half with the smallest at the pivot. As long as the seats stay balanced in count, the median is whatever sits right at the pivot point.
- Input
- addNum(1); addNum(2); findMedian(); addNum(3); findMedian()
- Output
- 1.5 then 2.0
- Why
- After 1 and 2 the median is (1+2)/2 = 1.5; after adding 3 the sorted stream is [1,2,3] with median 2.
-10^5 <= num <= 10^5There will be at least one element before findMedian is calledUp to 5 * 10^4 calls to addNum and findMedian