295. Find Median from Data Stream LeetCode Solution
In this guide, you will get 295. Find Median from Data Stream LeetCode Solution with the best time and space complexity. The solution to Find Median from Data Stream problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Find Median from Data Stream solution in C++
- Find Median from Data Stream solution in Java
- Find Median from Data Stream solution in Python
- Additional Resources
Problem Statement of 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 is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder() initializes the MedianFinder object.
void addNum(int num) adds the integer num from the data stream to the data structure.
double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input
[“MedianFinder”, “addNum”, “addNum”, “findMedian”, “addNum”, “findMedian”]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]
Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
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.
Follow up:
If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
Complexity Analysis
- Time Complexity: O(n\log n)
- Space Complexity: O(n)
295. Find Median from Data Stream LeetCode Solution in C++
class MedianFinder {
public:
void addNum(int num) {
if (maxHeap.empty() || num <= maxHeap.top())
maxHeap.push(num);
else
minHeap.push(num);
// Balance the two heaps s.t.
// |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1.
if (maxHeap.size() < minHeap.size())
maxHeap.push(minHeap.top()), minHeap.pop();
else if (maxHeap.size() - minHeap.size() > 1)
minHeap.push(maxHeap.top()), maxHeap.pop();
}
double findMedian() {
if (maxHeap.size() == minHeap.size())
return (maxHeap.top() + minHeap.top()) / 2.0;
return maxHeap.top();
}
private:
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<>> minHeap;
};
/* code provided by PROGIEZ */
295. Find Median from Data Stream LeetCode Solution in Java
class MedianFinder {
public void addNum(int num) {
if (maxHeap.isEmpty() || num <= maxHeap.peek())
maxHeap.offer(num);
else
minHeap.offer(num);
// Balance the two heaps s.t.
// |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1.
if (maxHeap.size() < minHeap.size())
maxHeap.offer(minHeap.poll());
else if (maxHeap.size() - minHeap.size() > 1)
minHeap.offer(maxHeap.poll());
}
public double findMedian() {
if (maxHeap.size() == minHeap.size())
return (double) (maxHeap.peek() + minHeap.peek()) / 2.0;
return (double) maxHeap.peek();
}
private Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
private Queue<Integer> minHeap = new PriorityQueue<>();
}
// code provided by PROGIEZ
295. Find Median from Data Stream LeetCode Solution in Python
class MedianFinder:
def __init__(self):
self.maxHeap = []
self.minHeap = []
def addNum(self, num: int) -> None:
if not self.maxHeap or num <= -self.maxHeap[0]:
heapq.heappush(self.maxHeap, -num)
else:
heapq.heappush(self.minHeap, num)
# Balance the two heaps s.t.
# |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1.
if len(self.maxHeap) < len(self.minHeap):
heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))
elif len(self.maxHeap) - len(self.minHeap) > 1:
heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap))
def findMedian(self) -> float:
if len(self.maxHeap) == len(self.minHeap):
return (-self.maxHeap[0] + self.minHeap[0]) / 2.0
return -self.maxHeap[0]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.