HardHeap / Priority Queue
Find Median from Data Stream
Find median with streaming numbers
Solution Approach
Two heaps: max heap for smaller half, min heap for larger half. Keep balanced.
Implementation
from heapq import heappush, heappop
class MedianFinder:
def __init__(self):
self.small = [] # max heap (negative values)
self.large = [] # min heap
def addNum(self, num):
if not self.small or num <= -self.small[0]:
heappush(self.small, -num)
else:
heappush(self.large, num)
# Balance heaps
if len(self.small) > len(self.large) + 1:
heappush(self.large, -heappop(self.small))
elif len(self.large) > len(self.small):
heappush(self.small, -heappop(self.large))
def findMedian(self):
if len(self.small) > len(self.large):
return float(-self.small[0])
return (-self.small[0] + self.large[0]) / 2Complexity Analysis
Time Complexity
O(log n)Space Complexity
O(n)Complexity
Time:O(log n)
Space:O(n)
Asked at
GoogleAmazonMicrosoft