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:
- You need the median or another middle value of a stream as numbers arrive.
- You must repeatedly split items into a "lower half" and "upper half."
- The problem mentions a sliding window median.
- You're balancing two groups, such as picking projects to maximize capital, where one heap holds options you can't afford yet and another holds options you can.
If the question only needs the smallest or largest k items, a single heap is usually enough.
The core idea
- Low is a max-heap holding the smaller half.
- High is a min-heap holding the larger half.
- Every element in low is less than or equal to every element in high.
- The sizes differ by at most one. A common convention: low may hold one extra element.
Then the median is:
- The top of low, if low has more elements.
- The average of both tops, if the sizes are equal.
Insertion in three steps
- Push the new number into low.
- Move low's top into high. This guarantees the ordering property.
- 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:
- Add 5: low [5], high [] → median 5.
- Add 2: low [2], high [5] → median 3.5.
- Add 8: low [5, 2], high [8] → median 5.
- Add 3: low [3, 2], high [5, 8] → median 4.
Tracing like this in the interview catches sign errors and balance bugs before the interviewer does.
Complexity
- Insert: O(log n).
- Median: O(1).
- Space: O(n).
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
- Asking for the median before any insert. Decide whether to raise an error or return a sentinel.
- Even versus odd counts and whether the average should be a float.
- Duplicates, which the pattern handles naturally.
- Very large values where averaging could overflow in fixed-width languages; compute
a + (b - a) / 2.
How to explain it in the interview
- Name the naive approach and its cost.
- Describe the two halves and the invariant: everything in low is at most everything in high, and sizes differ by at most one.
- Explain insertion and how balance is restored.
- Code it, then trace a four-element example.
- State the complexity and mention a variant if time allows.
Practice problems to try
- Find median from a data stream.
- Sliding window median.
- IPO or maximize capital.
- Running percentile of response times.
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/.
Rehearse with an AI interview copilot, then browse commonly reported interview questions.