Skip to content
BytePatterns

Running Median Stream

HardHeaps#two-heaps#streaming~45m

Problem

Numbers arrive one at a time. After each arrival, report the median of everything received so far: the middle value when the count is odd, and the average of the two middle values when it is even. Return the list of medians, one per arrival, as decimal numbers. The values do not arrive in any particular order.

Examples

Input:  stream = [5, 15, 1, 3]
Output: [5.0, 10.0, 5.0, 4.0]
Why:    after three arrivals the values are 1, 5, 15 and the middle one is 5
Input:  stream = [1, 2]
Output: [1.0, 1.5]
Why:    an even count averages the two middle values
Input:  stream = [7]
Output: [7.0]
Why:    edge case, a single value is its own median

Hints

0 / 3

Stuck on the idea rather than the code? Priority Queue covers it.