Implement addNum(num) and findMedian() for a stream of integers.
Before you code
Keeping a sorted list makes each insert O(n). The median only depends on the two values in the middle, which are the largest of the lower half and the smallest of the upper half: the roots of two heaps.
Hints
lowis a max-heap (negate values in Python);highis a min-heap.- Push into
low, then movelow's root tohigh, then ifhighis bigger, move its root back. That keeps the order and the sizes in one routine. - The median is
low's root if it has more elements, otherwise the average of both roots.
Production & complexity notes
When solving Find median from data stream on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.
What it practices
Two heaps meeting in the middle, from Top-k and merging streams.