InterviewHubPRO
Section Overview
Q68

Question 68 of 100

Part 8: Heaps, Priority Queues & Tries (65 - 72)

68%
DSA Patterns (Multi-Lang)•Part 8: Heaps, Priority Queues & Tries (65 - 72)

Find Median from Data Stream.

In Simple Words: Two Heaps balancing:

  • small: Max-Heap for lower half of numbers.
  • large: Min-Heap for upper half. Keep sizes balanced such that small.size == large.size or small.size == large.size + 1.
  • Time: addNum: $O(\log N)$, findMedian: $O(1)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
import heapq

class MedianFinder:
    def __init__(self):
        self.small = []  # max-heap (negated)
        self.large = []  # min-heap

    def addNum(self, num: int) -> None:
        heapq.heappush(self.small, -num)
        # small's max <= large's min
        if self.small and self.large and (-self.small[0] > self.large[0]):
            heapq.heappush(self.large, -heapq.heappop(self.small))
        # balance sizes
        if len(self.small) > len(self.large) + 1:
            heapq.heappush(self.large, -heapq.heappop(self.small))
        if len(self.large) > len(self.small):
            heapq.heappush(self.small, -heapq.heappop(self.large))

    def findMedian(self) -> float:
        if len(self.small) > len(self.large):
            return float(-self.small[0])
        return (-self.small[0] + self.large[0]) / 2.0