Find Median from Data Stream
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. Implement the `MedianFinder` class: * `addNum(num: number): void` adds the integer `num` from the data stream to the data structure. * `findMedian(): number` returns the median of all elements so far. **Examples:** ```typescript const medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: addNum: O(n), findMedian: O(1)
- Space complexity: O(n)
Binary search insertion takes O(n) for array shift; with two heaps (min-heap/max-heap) addNum is O(log n).
Follow-Up Questions Interviewers Ask About Find Median from Data Stream
- How do you achieve O(log n) addition using two heaps?
Maintain a max-heap for the smaller half of numbers and a min-heap for the larger half, balancing their sizes so they differ by at most 1.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.