01 · Question
Implement add(value) and median() for a stream of integers. The median is the middle value for odd size and the average of the two middle values for even size. Querying an empty stream returns None in Python or (0, false) in Go.
Example: after adding 5, 1, 9, 2, the successive medians are 5, 3, 5, 3.5.
02 · Analysis
The lower half is a max-heap and the upper half a min-heap. Insert relative to the upper root, then rebalance so the upper heap has the same size or one more item. Ordering across the halves plus the size rule places the median at their roots. In Python, negate lower-half values to simulate a max-heap. Add costs O(log n), lookup O(1), storage O(n). Median results use floating-point arithmetic; exact rational output would need a different return type.