Find Median from Data Stream - Problem
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.
For example:
- For
arr = [2,3,4], the median is3 - For
arr = [2,3], the median is(2 + 3) / 2 = 2.5
Implement the MedianFinder class:
MedianFinder()initializes the MedianFinder objectvoid addNum(int num)adds the integernumfrom the data stream to the data structuredouble findMedian()returns the median of all elements so far
Answers within 10⁻⁵ of the actual answer will be accepted.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"], values = [null,1,2,null,3,null]
›
Output:
[null,null,null,1.5,null,2.0]
💡 Note:
Initialize finder, add 1, add 2, find median (1+2)/2=1.5, add 3, find median 2.0
Example 2 — Single Element
$
Input:
operations = ["MedianFinder","addNum","findMedian"], values = [null,5,null]
›
Output:
[null,null,5.0]
💡 Note:
With only one element, the median is that element itself
Example 3 — Negative Numbers
$
Input:
operations = ["MedianFinder","addNum","addNum","findMedian"], values = [null,-1,-2,null]
›
Output:
[null,null,null,-1.5]
💡 Note:
With -1 and -2, the median is (-1 + -2) / 2 = -1.5
Constraints
- -105 ≤ num ≤ 105
- There will be at least one element in the data structure before calling findMedian
- At most 5 × 104 calls will be made to addNum and findMedian
Visualization
Tap to expand
Understanding the Visualization
1
Input Stream
Operations: addNum(1), addNum(2), findMedian()
2
Data Structure
Maintain sorted order or balanced partitions
3
Output
Return median values: 1.5
Key Takeaway
🎯 Key Insight: Two balanced heaps allow O(log n) insertions with O(1) median queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code