Skip to the solution
MediumDSA13 min read

Find median from data stream with two heaps — invariant and rebalancing?

179 views

The problem

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: heapq is 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.

  • heap
  • design
  • Amazon

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read · 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTrace: route, rebalance and median for seven adds
PythonInvariant check on 5000 adds, two strategies, overflow pairs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 117 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you build a binary tree from preorder and inorder traversals?

Continue