Coders Crushby Napplied AI
Back to DSA Problems
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]) / 2
Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(n)
Complexity
Time:O(log n)
Space:O(n)
Asked at
GoogleAmazonMicrosoft
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless