My first instinct was binary search insertion into a sorted array which is what the prompt basically hints at, but then they asked about the time complexity and I had to admit that shifting elements on insert is O(n).
Start by clarifying the problem constraints (e.g., data types, stream size, memory limits) and then propose a two-heap solution: a max-heap for the lower half and a min-heap for the upper half. Explain how to maintain balance and compute the median in O(1) time after each insertion, with O(log n) insertion time.
Pro tip: Mention that you would handle edge cases like even/odd number of elements and discuss potential optimizations such as using a self-balancing BST if the stream is extremely large and heaps are not feasible due to memory constraints.
Ask about the nature of the stream (e.g., integers, floats), expected size, and whether memory is a constraint. Confirm that the median should be returned after each insertion.
Suggest using two heaps: a max-heap for the smaller half and a min-heap for the larger half. Explain that this allows O(1) median retrieval and O(log n) insertion.
Describe the algorithm: add the new number to the appropriate heap, then rebalance so that the size difference between heaps is at most 1. Ensure the max-heap's top is <= min-heap's top.
Explain that if heaps are equal size, median is the average of the two tops; otherwise, it's the top of the larger heap.
State time complexity: O(log n) per insertion, O(1) for median. Discuss edge cases: empty stream, single element, duplicates, and potential overflow when averaging.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.