Keep the running median as numbers stream in. Split them across two heaps, a max-heap for the low half and a min-heap for the high half.
▼The problem
LeetCode 295 (Hard). Design a MedianFinder with addNum(num), which adds a number from a stream, and findMedian(), which returns the median of every number added so far (the average of the two middle values when the count is even).
Example (kept from the original): adding 5, 15, 1, 3, 8 gives medians 5, 10, 5, 4, 5.
import heapq
class MedianFinder:
def __init__(self):
self.low, self.high = [], [] # max (negated), min
def addNum(self, num):
if not self.low or num <= -self.low[0]:
heapq.heappush(self.low, -num)
else:
heapq.heappush(self.high, num)
if len(self.low) > len(self.high) + 1:
heapq.heappush(self.high, -heapq.heappop(self.low))
elif len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def findMedian(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2TRY IT ON LEETCODE ▶The solution
import heapq
class MedianFinder:
def __init__(self):
self.low, self.high = [], [] # max (negated), min
def addNum(self, num):
if not self.low or num <= -self.low[0]:
heapq.heappush(self.low, -num)
else:
heapq.heappush(self.high, num)
if len(self.low) > len(self.high) + 1:
heapq.heappush(self.high, -heapq.heappop(self.low))
elif len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def findMedian(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2Transcript
Find Median from Data Stream. Numbers arrive one at a time, and after each one, we must report the median: the middle value of everything so far. With an even count, it's the average of the two middle values.
Say five, fifteen, one and three have arrived. Sorted, that's one, three, five, fifteen. The middle pair is three and five, so the median is four.
The simple way keeps a sorted list. Reading the middle is instant, but each new number must be slotted in, and everything after it shifts over. That's order n work for every add.
But we only need the middle. So split the numbers into two halves. The lower half is a max heap, with its biggest on top. The upper half is a min heap, with its smallest on top. Put them on a seesaw, and the two tops meet in the middle.
Keep it balanced: both sides equal, or the low side one bigger. Then the median sits at the pivot: the low side's top, or the average of the two tops.
Let's add five, fifteen, one, three and eight. Five goes low: median five. Fifteen is bigger, so it goes high: median ten. One goes low: five. Three goes low too, and now low is two ahead, so its top, five, slides across. The median is three plus five over two: four. Eight goes high, and now high is bigger, so five slides back. Median five.
In code, Python's heap is a min heap, so the low side stores negated numbers. Push onto the low side if the number is at most its top, otherwise onto the high side. If low gets two ahead, or high gets bigger, pop a top across. Find median just reads the tops.
Each add is a few heap pushes and pops: order log n. The median reads two tops: order one. And the heaps hold every number: order n space.
Two halves, two heaps, balanced on the middle. That's Find Median from Data Stream.