Algorithm Day77 - Find Median from Data Stream
🧩 Problem Description
The MedianFinder class:
MedianFinder()
initializes the object.void addNum(int num)
adds the integernum
to the data structure.double findMedian()
returns the median of all elements so far.
💬 Examples
Example 1
1 | Input: |
💡 Intuition
To efficiently find the median:
Use two heaps:
- A max-heap (left) to store the smaller half of numbers.
- A min-heap (right) to store the larger half of numbers.
Balancing rule:
- Either both heaps have equal size, or left has one more element.
- Median = root of max-heap (if odd) or average of roots (if even).
🔢 Java Code (Two Heaps)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time (per operation): O(log n)
- Space: O(n)
✍️ Summary
- Two Heaps maintain balance between left and right halves.
- Ensures O(log n) per insertion and O(1) median query.
Related problems
lc-480
— Sliding Window Medianlc-703
— Kth Largest Element in a Streamlc-220
— Contains Duplicate III