Practice Problem
Find Median from Data Stream
Difficulty: Hard
Design a data structure that efficiently finds the median from a stream of integers using two heaps.
Find Median from Data Stream
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 example, for
arr = [2, 3], the median is(2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder(): Initializes theMedianFinderobject.addNum(num): Adds the integernumfrom the data stream to the data structure.findMedian(): Returns the median of all elements so far. Answers within10^-5of the actual answer will be accepted.
Examples
Example 1:
Input:
MedianFinder()
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2.0Example 2:
Input:
MedianFinder()
addNum(6)
findMedian() -> 6.0
addNum(10)
findMedian() -> 8.0
addNum(2)
findMedian() -> 6.0
addNum(6)
findMedian() -> 6.0Constraints
-10^5 <= num <= 10^5- There will be at least one element in the data structure before calling
findMedian. - At most
5 * 10^4calls will be made toaddNumandfindMedian.
Expected Complexity
- Time: O(log n) per
addNum, O(1) perfindMedian - Space: O(n)
HARD
Heap
Min Heap
Max Heap
Priority Queue
Median Finding
Data Structures
Advanced
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
