Skip to content

How to Fix Find Median from Data Stream Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Find Median from Data Stream Errors. We cover key concepts, practical examples, and best practices.

Fix find median from data stream errors when two heaps not balanced or median calculated incorrectly.

Quick Fix

Wrong

def add(n):
    arr.append(n)
def median():
    arr.sort()
    return arr[len(arr)//2]

O(n log n) per median query. No streaming optimization.

import heapq
class Median:
    def __init__(self):
        self.lo=[]  # max-heap via negative
        self.hi=[]  # min-heap
    def add(self,n):
        heapq.heappush(self.lo,-n)
        heapq.heappush(self.hi,-heapq.heappop(self.lo))
        if len(self.lo)<len(self.hi):
            heapq.heappush(self.lo,-heapq.heappop(self.hi))
    def median(self):
        if len(self.lo)>len(self.hi): return -self.lo[0]
        return (-self.lo[0]+self.hi[0])/2
add(1),add(2),median()->1.5,add(3),median()->2. O(log n) each.

Prevention

Two heaps: max-heap for lower half, min-heap for upper half. Balance sizes.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is median stream?

Running median with O(log n) inserts. Two-heap technique.

Max-heap simulation?

Python has min-heap only. Store negatives for max-heap behavior.

Balance condition?

len(lo) == len(hi) or len(lo) == len(hi)+1.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro