Two heaps was the obvious move and I got there fast, but then they pushed on the invariants and I fumbled a bit.
Start by clarifying the API and constraints, then propose a two-heap solution (max-heap for lower half, min-heap for upper half) that maintains balance and ordering. Walk through the invariants, complexity proofs, and implement the core methods, discussing trade-offs and edge cases.
Pro tip: Emphasize that the two-heap approach naturally handles duplicates and even/odd counts, and mention that you can optimize by using a single array with binary search for O(log n) insertion and O(1) median retrieval if memory is not a concern.
Define the API: addNum(int num) and findMedian(). Clarify constraints: up to 1M operations, duplicates allowed, even/odd counts. Discuss expected time complexities.
Propose two heaps: a max-heap for the lower half and a min-heap for the upper half. State invariants: max-heap size equals min-heap size or differs by 1; all elements in max-heap ≤ all elements in min-heap.
Show that addNum is O(log n) due to heap insertions and rebalancing, and findMedian is O(1) by peeking at heap tops. Prove that invariants guarantee the median is at the top(s).
Write code for addNum and findMedian, handling rebalancing and edge cases (empty stream, duplicates). Use a max-heap implemented via negative values in a min-heap if needed.
Mention alternative approaches like a balanced BST or a sorted array with binary search, comparing time/space trade-offs. Highlight why two heaps is optimal for this scenario.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.