Running median with two heaps
Asked at HRT, Two Sigma
Prices arrive one at a time. After each arrival, report the median of everything seen so far, a robust mid-price estimate that outliers can't drag around.
add(5) -> median 5
add(3) -> median 4.0 # of {3, 5}
add(8) -> median 5 # of {3, 5, 8}
add(9) -> median 6.5 # of {3, 5, 8, 9}
Support add in and median in . Re-sorting per tick is ; keeping a sorted list with insertion is per add because of element shifting.
Show a hint
The median splits the data into a lower half and an upper half. Which data structure hands you the maximum of the lower half and the minimum of the upper half cheaply?
Your answer
This one is open-ended. Work it through, then check your reasoning against the full solution.