Two Heaps Interview Pattern: Running Median and Balanced Splits

Two Heaps Interview Pattern: Running Median and Balanced Splits

Some interview problems ask you to keep track of the "middle" of a changing set of numbers. Sorting after every insert is too slow. The two heaps interview pattern solves this neatly: keep the smaller half of the numbers in a max-heap and the larger half in a min-heap. The tops of the two heaps sit right at the middle.

This guide explains when to use it, how to implement it, and how to talk through it in an interview.

When to reach for two heaps

Look for these signals:

If the question only needs the smallest or largest k items, a single heap is usually enough.

The core idea

Then the median is:

Insertion in three steps

  1. Push the new number into low.
  2. Move low's top into high. This guarantees the ordering property.
  3. If high now has more elements than low, move high's top back into low.

Each insert does a constant number of heap operations, so it's O(log n). Reading the median is O(1).

Python sketch

Python's heapq is a min-heap, so store negated values in low:

import heapq

class MedianFinder:
    def __init__(self):
        self.low = []   # max-heap via negatives
        self.high = []  # min-heap

    def add(self, num):
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

Say the negation trick out loud. Interviewers want to know you understand why the signs flip.

Walk through a small example

Add 5, 2, 8, 3:

Tracing like this in the interview catches sign errors and balance bugs before the interviewer does.

Complexity

Compare it to alternatives: sorting after each insert costs O(n log n) per query, and inserting into a sorted list costs O(n) per insert because of shifting.

Common variants

Sliding window median. You also need to remove elements as the window moves. Heaps don't support efficient arbitrary deletion, so a common approach is lazy deletion: record items to remove in a hash map and discard them when they reach a heap's top. Keep separate counts of the valid sizes. Mention that a balanced binary search tree or sorted container is an alternative in languages that have one.

Maximize capital (IPO-style). Sort projects by required capital and push affordable ones into a max-heap by profit. Each round, take the best affordable project. This uses the same two-group thinking.

Percentile other than median. Change the balance rule so low holds a fixed fraction of elements instead of half.

Edge cases to mention

How to explain it in the interview

  1. Name the naive approach and its cost.
  2. Describe the two halves and the invariant: everything in low is at most everything in high, and sizes differ by at most one.
  3. Explain insertion and how balance is restored.
  4. Code it, then trace a four-element example.
  5. State the complexity and mention a variant if time allows.

Practice problems to try

Practice the explanation, not just the code

The two heaps pattern is short to code but easy to fumble live, especially the sign trick and balance step. Rehearse it with a timer and out loud.

Luna Interview is a practice and calm-under-pressure companion for exactly that, with timed sessions and structured hints in your browser. Try Luna Interview at https://lunainterview.xyz/.