Two Heaps

Advanced optimization. The elite pattern for tracking the running median in a continuous data stream.

Recognition

  • Need a running median or balanced split of a stream.
  • You repeatedly need the current largest of one half and smallest of the other.

When not to use it

Do not force this pattern when the input is unordered and hashing is enough.

Avoid coding the template before naming the invariant you need to preserve.

Logic template

Python

class MedianFinder:
    def __init__(self):
        self.small = [] # Max-heap (stores smaller half)
        self.large = [] # Min-heap (stores larger half)

    def addNum(self, num):
        # Push to small, then move largest of small to large
        heapq.heappush(self.small, -num)
        heapq.heappush(self.large, -heapq.heappop(self.small))
        
        # Maintain size property: len(small) >= len(large)
        if len(self.large) > len(self.small):
            heapq.heappush(self.small, -heapq.heappop(self.large))

JavaScript

class MedianFinder {
  constructor() {
    this.small = new MaxPriorityQueue(); // stores smaller half
    this.large = new MinPriorityQueue(); // stores larger half
  }

  addNum(num) {
    this.small.enqueue(num);
    this.large.enqueue(this.small.dequeue().element);
    
    if (this.large.size() > this.small.size()) {
      this.small.enqueue(this.large.dequeue().element);
    }
  }
}

Typically better than the obvious O(N^2) approach; verify with the template.

  • Name what stays true after every move.
  • Track the exact condition that lets you discard work safely.

Worked example

Recognition drill

Identify the reusable state and the rule that advances it.

  1. Restate the goal in one sentence.
  2. Name the moving parts and what they represent.
  3. Write the loop invariant before coding.
  4. Trace one failing case that breaks a naive approach.

Result: You can explain when to reach for the pattern and when to abandon it.

Common pitfalls

  • Off-by-one updates on loop bounds.
  • Updating state after comparing instead of before.
  • Confusing “solved once” with pattern mastery.

Related practice problems