Design a data structure that supports adding integers from a data stream and querying the median of all values received so far.
The median is the middle value of an ordered list. When the count of values is odd it is the single middle element; when the count is even it is the average of the two middle elements.
Implement the class:
- `MedianFinder()` initializes the structure. - `addNum(num)` ingests the next integer from the stream. - `findMedian()` returns the median of every value added so far as a floating-point number.
Example 1
Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"] [[],[1],[2],[],[3],[]]
Output: [null, null, null, 1.5, null, 2.0]
After adding 1 and 2 the median is (1 + 2) / 2 = 1.5. After adding 3 the sorted values are [1, 2, 3], so the median is 2.0.
Example 2
Input: ["MedianFinder","addNum","findMedian","addNum","findMedian"] [[],[5],[],[10],[]]
Output: [null, null, 5.0, null, 7.5]
With only 5 present the median is 5.0; after adding 10 the median is (5 + 10) / 2 = 7.5.
Constraints
-10^5 <= num <= 10^5There is at least one element before findMedian is called.At most 5 * 10^4 calls are made to addNum and findMedian.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI