Question presented to candidate:
"Numbers arrive one at a time. Design a Python class with add_num(x) and find_median(), where find_median returns the median of everything added so far. Both calls happen many times, so tell me the cost of each."
What a strong answer should cover:
- Why sorting on every query (O(n log n)) and keeping a sorted list (O(n) per insert) are too slow for long streams.
- Two heaps: a max-heap for the lower half and a min-heap for the upper half; O(log n) add, O(1) median.
- The invariant: every number in the lower half โค every number in the upper half, and the sizes differ by at most one.
- Python details:
heapqis a min-heap only, so the lower half stores negated values; use/ 2(true division) for the even case, not// 2. - Follow-ups: values in a small range (counting buckets), removals (sliding window), percentiles other than 50%.
Clarifying questions expected:
- For an even count, average the two middle values or return the lower one?
- What range can the values take, and can they be removed?
Code / implementation expected: Yes โ a MedianFinder class built on two heapq lists, in Python 3.