Question presented to candidate:
"You are keeping a running median with two heaps in Python. State the invariant precisely, explain why it gives you the median, and show how add_num restores it after every insert. Why is one move between the heaps always enough?"
What a strong answer should cover:
- The order rule (max of the lower half ≤ min of the upper half) and the size rule (sizes equal, or the lower half has one more).
- Why the two rules together put the median at the tops: positions |low| and |low| + 1 in sorted order.
- The routing step and the case analysis showing one move restores the size rule; the order rule survives both routing and the move.
- The two common strategies (compare-first vs push-through) and their cost in heap operations.
- Python details:
heapqis min-only, so the lower half stores negated values and every move must negate exactly once;/ 2, not// 2.
Code / implementation expected: Optional — an add method plus an invariant_ok check in Python 3.