How would you maintain a running median over a stream of incoming values, and why is a two-heap design the standard approach rather than keeping a sorted list?

technical-conceptual · Senior level · software-engineering

What the interviewer is really asking

Assesses whether the candidate can design the two-heap (max-heap/min-heap) running-median structure, reason about the rebalancing invariant and its O(log n) insert versus a sorted list's O(n) insertion, and handle the parity and removal edge cases.

What to say

What to avoid

Example answers

Strong: I keep two heaps: a max-heap for the lower half and a min-heap for the upper half, with their sizes differing by at most one. On each value I push to the correct side based on the current median, then rebalance by moving one element across if a heap got two ahead. The median is the larger heap's top, or the average of both tops when counts are equal — O(1) to read, O(log n) to insert. A sorted list reads the median in O(1) but costs O(n) per insert because you shift to stay sorted, which is too slow for a busy stream. If I also need to evict old values for a sliding window, I'd add lazy deletion or switch to an order-statistics tree.

Weak: I'd keep the numbers in a sorted list and on each insert put the value in the right spot, then read the middle element. Insertion keeps it sorted so the median is always just the center.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.