The trick is knowing to reach for two heaps immediately.
Use two heaps (a max-heap for the lower half and a min-heap for the upper half) to maintain the median in O(log n) insertion and O(1) retrieval. Explain how to balance the heaps after each insertion and handle even/odd total counts.
Pro tip: Discuss the trade-offs between this heap-based approach and alternatives like a balanced BST or sorted list, and mention how you would handle duplicates and large streams.
Ask about the expected number of elements, frequency of median queries, and whether the stream is unbounded. Confirm that the median is the middle value for odd counts and the average of two middle values for even counts.
Describe using a max-heap to store the smaller half and a min-heap to store the larger half. Explain that this keeps the median at the top of one or both heaps.
Explain the algorithm: add the new number to the appropriate heap, then rebalance by moving the top element if the size difference exceeds 1. Ensure the max-heap's top is <= the min-heap's top.
If the heaps are equal in size, the median is the average of their tops; otherwise, it's the top of the larger heap. This gives O(1) retrieval.
State that insertion is O(log n) and median retrieval is O(1), with O(n) space. Discuss handling empty stream, single element, and duplicates.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.