imashutosh51

Find Median from Data Stream

May 5th, 2026
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. '''
  2. Maintain 2 heaps, first one(Max heap) should be containing left half of all the elements seen and put it into the sorted order and vice versa for other one(Min heap).
  3.  
  4. left_half and right_half can have either same size or left_half can have one element more.
  5. so directly push a new element into the right_heap and then check is the right_heap size is greater than left or not, if greater then right_heap top will be having the smallest element of the right_half so pop that element and push it into the left heap,that's all.
  6. While returning the median, if sum of length of both equal to even, return the mean of the top two elements of the heaps else return the left heap top element.
  7. '''
  8.  
  9. from heapq import heappush, heappop
  10. class MedianFinder:
  11.  
  12.     def __init__(self):
  13.         self.left_heap = []   # max heap (store negative)
  14.         self.right_heap = []  # min heap
  15.  
  16.     def addNum(self, num: int) -> None:
  17.         # Step 1: push to max heap
  18.         heappush(self.left_heap, -num)
  19.        
  20.         # Step 2: balance → move max of left to right
  21.         heappush(self.right_heap, -heappop(self.left_heap))
  22.        
  23.         # Step 3: maintain size property
  24.         if len(self.right_heap) > len(self.left_heap):
  25.             heappush(self.left_heap, -heappop(self.right_heap))
  26.  
  27.     def findMedian(self) -> float:
  28.         if len(self.left_heap) > len(self.right_heap):
  29.             return -self.left_heap[0]
  30.         else:
  31.             return (-self.left_heap[0] + self.right_heap[0]) / 2
Advertisement
Add Comment
Please, Sign In to add comment