Find Median from Data Stream — C# Coding Problem
Difficulty: hard | Category: heap
Problem Description
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: - `MedianFinder()` initializes the object. - `void addNum(int num)` adds the integer `num` from the data stream to the data structure. - `double findMedian()` returns the median of all elements so far. **Approach:** Use two heaps — a max-heap for the lower half and a min-heap for the upper half. Balance them so their sizes differ by at most 1.
Examples
Example 1
Input: MedianFinder mf; mf.addNum(1); mf.addNum(2); mf.findMedian(); mf.addNum(3); mf.findMedian();
Output: 1.5, 2.0