The middle value so far
Report the median of a stream after each new number, by keeping the smaller half in a max-heap and the larger half in a min-heap. About 22 minutes.
Two halves
The median is the middle of the sorted numbers. Instead of sorting, keep two groups: the smaller half and the larger half. Every number in the small group is no bigger than every number in the large group.
The small group lives in a max-heap, so its biggest number is on top. The large group lives in a min-heap, so its smallest is on top. The median is made from these two tops.
if len(low) == len(high):
median = (-low[0] + high[0]) / 2
else:
median = -low[0]Only 4. The median is 4, twice that is 8.
Add, pass across, rebalance
To add a number, put it into the low half. Then move the biggest of the low half across to the high half. This guarantees that every low number is at most every high number.
Then rebalance: the low half may hold at most one more number than the high half. If the high half became bigger, move its smallest back. If the counts are equal, the median is the average of the two tops; otherwise it is the top of the low half.
if len(high) > len(low):
top = heapq.heappop(high)
heapq.heappush(low, -top)The low half has 3 numbers and the high half has 3 numbers. What is the median?
- AThe average of the top of the low half and the top of the high half
- BThe top of the low half
- CThe top of the high half
Show the answer
The average of the top of the low half and the top of the high half. With an even count, the median is the average of the two middle numbers.
Running median, doubled
Numbers arrive one at a time in the array nums. After each arrival, find the median of all numbers so far: the middle number if the count is odd, or the average of the two middle numbers if it is even. Because the average can end in .5, return twice the median each time, so the answers are whole numbers. Return the list with one entry per arrival.
nums = [5, 2, 8, 1] → [10, 7, 10, 7]
0 ≤ length of nums ≤ 3,000 · -10,000 ≤ nums[i] ≤ 10,000