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