Find Median from Data Stream
Support addNum and findMedian as numbers stream in, both fast.
Intuition
Keep the lower half in a max-heap and the upper half in a min-heap. The median is at the roots — no scanning. Each insert goes into one heap and rebalances at most one element across, so both roots always face the middle.
Approach
Two heaps face each other
lo (max-heap) holds the smaller half, hi (min-heap) the larger. Invariant: every lo element ≤ every hi element, sizes differ by ≤ 1.
Insert then rebalance
Push into lo, move lo's max to hi (guaranteeing the ordering invariant), then if hi outgrew lo, move hi's min back. Two heap ops, done.
Median from the roots
Odd count → lo's root (lo is the bigger heap). Even → average of both roots. O(1).
Solution & live demo
Edge cases
Rebalancing keeps halves even regardless of arrival order.
Invariant is ≤ so equal values may sit on both sides — fine.