← Trexquant Interview Insights
The two-heap approach is the right answer here and I knew it, but I fumbled the balancing logic under pressure.
Use two heaps: a max-heap for the lower half and a min-heap for the upper half, keeping their sizes balanced. After each insertion, rebalance and compute the median from the top elements. This gives O(log n) insertion and O(1) median retrieval.
Pro tip: Explicitly discuss edge cases like empty stream and even/odd counts, and mention that this approach is optimal for streaming data because it avoids sorting on each query.
Ask about the expected frequency of insertions vs. median queries, memory limits, and whether the stream can be empty. This shows you consider real-world usage.
Explain that a max-heap stores the smaller half and a min-heap stores the larger half, with size difference at most 1. This maintains the median at the tops.
Describe adding to the appropriate heap, then moving the top element if sizes differ by more than 1. Emphasize O(log n) time.
If heaps are equal size, median is the average of the two tops; otherwise, it's the top of the larger heap. This is O(1).
State time and space complexity, and discuss handling empty stream, even/odd counts, and potential integer overflow when averaging.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.