
Problem
Solution
Submissions
Find Median from Data Stream
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Design a data structure that supports the following two operations:
- addNum(int num): Add an integer to the data stream.
- findMedian(): Return the median of all elements in the stream.
The median is the middle value in an ordered list of numbers. If the list has an odd number of elements, the median is the middle element. If the list has an even number of elements, the median is the average of the two middle elements.
Example 1
- Input: ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
- Input: [[], [1], [2], [], [3], []]
- Output: [null, null, null, 1.5, null, 2.0]
- Explanation: MedianFinder object is instantiated. 1 is added to the stream. 2 is added to the stream. findMedian() returns 1.5 as the middle elements are 1 and 2, and their average is 1.5. 3 is added to the stream. findMedian() returns 2.0 as the middle element is 2.
Example 2
- Input: ["MedianFinder", "addNum", "findMedian", "addNum", "findMedian"]
- Input: [[], [5], [], [10], []]
- Output: [null, null, 5.0, null, 7.5]
- Explanation: MedianFinder object is instantiated. 5 is added to the stream. findMedian() returns 5.0 as there is only one element. 10 is added to the stream. findMedian() returns 7.5 as the middle elements are 5 and 10, and their average is 7.5.
Constraints
- -10^5 <= num <= 10^5
- There will be at least one element in the data structure before calling findMedian
- At most 5 * 10^4 calls will be made to addNum and findMedian
- The addNum operation should have a time complexity of O(log n)
- The findMedian operation should have a time complexity of O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two heaps: a max heap for the smaller half of the numbers and a min heap for the larger half
- Balance the heaps so that they have an equal number of elements (or the max heap has one more element for odd counts)
- The max heap stores the smaller half of numbers, and the min heap stores the larger half
- The top element of the max heap is the largest of the smaller half, and the top element of the min heap is the smallest of the larger half
- If the number of elements is odd, the median is the top of the max heap. If even, it's the average of the tops of both heaps