As asked
Design a data structure that supports two operations: addNum(int num) adds a number to the data stream, and findMedian() returns the median of all numbers added so far. What is the time complexity of each operation?
Sample answer outline
The classic solution uses two heaps: a max-heap for the lower half and a min-heap for the upper half, keeping them balanced in size. addNum is O(log n) and findMedian is O(1). The candidate should explain the balancing logic: after each insert, if the heaps differ in size by more than 1, move the top element from the larger heap to the smaller. Edge cases: empty stream, single element, even versus odd total count.
Expect these follow-ups
- How would you find the median of a sliding window of the last k elements?
- How does your solution handle integer overflow if values can be very large?