Find Median from Data Stream
Design a data structure that supports adding numbers and finding the median.
Examples
Input: [["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"],[[],[1],[2],[],[3],[]]]
Output: [null,null,null,1.5,null,2]
Input: [["MedianFinder","addNum","findMedian"],[[],[1],[]]]
Output: [null,null,1]
Hints
Implement the heaps such that the max-heap stores the lower half and the min-heap stores the upper half, ensuring the max-heap's top is always ≤ the min-heap's top.
After each insertion, rebalance the heaps if their sizes differ by more than 1 by moving elements between them.
For odd total elements, the median is the top of the larger heap; for even, it's the average of both heaps' tops. Optimize rebalancing to run in O(log n) time per operation.
Related Problems
Find Median from Data Stream
Design a data structure that supports adding numbers and finding the median.