How do you keep a running median as numbers arrive?
Question
Delivery times in minutes arrive one at a time. After each one, report the median of all times so far. For an even count, the median is the average of the two middle values.
Write a generator running_medians(stream) that yields the median after each number. Each new number should cost O(log n), not a full sort. Use Python 3.12 and heapq.
list(running_medians([30, 12, 45, 18, 18, 60])) # [30, 21.0, 30, 24.0, 18, 24.0]
import heapq def running_medians(stream): ...
Show hints (3)
- "SPLIT IN TWO"
You don't need the whole list in order. The median sits between the smaller half and the larger half. What do you need to see quickly in each half?
- "TWO HEAPS"
Keep the smaller half in a max-heap and the larger half in a min-heap. In Python 3.12
heapqonly gives min-heaps, so store the smaller half as negated numbers. - "TWO RULES"
After each add, keep two rules. Every value in the low half is at most every value in the high half. The low half has the same size as the high half, or one more.
Show checked explanation
Keep the smaller half in a max-heap and the larger half in a min-heap. In Python 3.12 the max-heap is a heapq list of negated numbers. Every low value must be at most every high value, and the low half has the same size or one more. The median is the low top, or the average of both tops.
import heapq def running_medians(stream): low, high = [], [] # low: smaller half, negated; high: larger half for x in stream: heapq.heappush(high, -heapq.heappushpop(low, -x)) if len(high) > len(low): heapq.heappush(low, -heapq.heappop(high)) if len(low) > len(high): yield -low[0] else: yield (-low[0] + high[0]) / 2 print(list(running_medians([30, 12, 45, 18, 18, 60]))) print(list(running_medians([])))
[30, 21.0, 30, 24.0, 18, 24.0] []
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the stream [30, 12, 45, 18, 18, 60]. Each new number first goes into the low half. Then the largest low value moves to the high half. If the high half is now bigger, its smallest value moves back.
| added | low half | high half | median |
|---|---|---|---|
| 30 | 30 | none | 30 |
| 12 | 12 | 30 | (12 + 30) / 2 = 21.0 |
| 45 | 12, 30 | 45 | 30 |
| 18 | 12, 18 | 30, 45 | (18 + 30) / 2 = 24.0 |
| 18 | 12, 18, 18 | 30, 45 | 18 |
| 60 | 12, 18, 18 | 30, 45, 60 | (18 + 30) / 2 = 24.0 |
The table shows the halves sorted, but inside the heaps they are not. Only the tops matter. Both 18s stay: they are two deliveries, not one.
The two rules do different jobs. The order rule (every low value is at most every high value) makes the two tops neighbours in sorted order. The size rule puts the split in the middle. Sizes alone are not enough. Put 12, 45 and 60 in the low half and 18, 18 and 30 in the high half. The sizes match, but the tops give (60 + 18) / 2 = 39.0 instead of 24.0.
Why does the first move keep the order rule? heapq.heappushpop(low, -x) adds the new number, then removes the largest value among the low half and the new number. Everything left in the low half is at most that value, so it can safely join the high half.
Each add does at most four heap operations, so it costs O(log n). Reading the tops is O(1).
Common mistakes
- Using
heapqas a max-heap without negating. In Python 3.12 it is a min-heap only, solow[0]is the smallest value. Functions likeheapq.heappush_maxonly arrived in Python 3.14. - Dropping repeated values with a set. Two deliveries of 18 minutes are two data points. After the fifth number the set gives 24.0 instead of 18.
- Writing
(a + b) // 2for an even count. It rounds down, so the median of 18 and 25 becomes 21 instead of 21.5.
Follow-up questions
- "The numbers are huge integers, like
2**60and2**60 + 1. What breaks?" A float holds every integer exactly only up to2**53. Here(a + b) / 2gives1.152921504606847e+18, which equals2**60exactly, but the true median is2**60 + 0.5. Returnfractions.Fraction(a + b, 2)instead. - "All times are whole minutes from 0 to 120. Can you do better?" Yes. Keep 121 counters, one per minute. Adding a time is O(1). Finding the median walks at most 121 counters, which does not grow with the number of deliveries. Heaps fit when the range of values is large or unknown.
- "Why not keep one sorted list with
bisect.insort?" Finding the place is O(log n), but inserting into a Python list shifts every item after it. So each add costs O(n). Two heaps keep each add at O(log n).
What a strong answer covers
Names both rules and why each one is needed. Builds the max-heap by negation and knows heapq has no public max-heap in 3.12. Keeps duplicates. Returns a true average for an even count and mentions float precision for huge numbers.
Open in interactive practice deck →