How do you find the Median from a Data Stream efficiently?
This problem asks to maintain the median of a stream of numbers as they arrive. It tests heap usage.
Why Interviewers Ask This
Interviewers ask this to test dynamic median maintenance. They want to see if you can use two heaps to balance the data. It demonstrates streaming algorithm skills.
How to Answer This Question
Explain using two heaps: a max-heap for the lower half and a min-heap for the upper half. Balance their sizes so the max-heap has one more element or they are equal. The median is the top of the max-heap or the average of both tops. Discuss insertion and balancing logic.
Key Points to Cover
- Two-heap structure
- Balancing strategy
- Median calculation logic
- Efficient updates
Sample Answer
I maintain two heaps: a max-heap for the lower half of numbers and a min-heap for the upper half. When a new number arrives, I add it to one of the heaps and then rebalance so the sizes differ by at most one. If the heap…
Common Mistakes to Avoid
- Incorrect balancing rules
- Wrong heap types (min vs max)
- Not handling even/odd counts
Sound confident on this question in 5 minutes
Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.