Median Tracker for an Incoming Number Feed
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Maintain the median of a growing sequence after each new value arrives, testing efficient order-statistic upkeep with a pair of heaps.
Median Tracker for an Incoming Number Feed
A sensor sends integer readings one at a time. The readings are given in arrival order in the list readings. Right after each reading arrives, you must record the median of every reading received up to and including that one.
Return a list with one median per arrival, in arrival order.
Definition of the median
Sort all readings received so far.
- If the count is odd, the median is the middle value of the sorted list.
- If the count is even, the median is the average of the two middle values of the sorted list.
Rules
- The result at index
iis the median ofreadings[0..i](inclusive). - Repeated values are distinct readings, and each one is counted.
- Every result must be a Python
float, including medians that are whole numbers (for example5.0, not5). - Each median is either a whole number or a whole number plus one half, so it can be represented exactly.
Constraints
1 <= len(readings) <= 5 * 10^4-10^5 <= readings[i] <= 10^5
Examples
Example 1
Input: running_median_feed([5, 2, 8, 1])
Output: [5, 3.5, 5, 3.5]
Example 2
Input: running_median_feed([-3, -3, 4])
Output: [-3, -3, -3]
Example 3
Input: running_median_feed([1, 10, 2, 9])
Output: [1, 5.5, 2, 5.5]
Hints
Hint 1
Re-sorting the whole prefix after every arrival is too slow for 50,000 values. Think about what you actually need: only the middle one or two elements.
Hint 2
Split the received values into a lower half and an upper half so that everything in the lower half is at most everything in the upper half. Which data structure gives quick access to the largest of one half and the smallest of the other?
Hint 3
Use a max-heap (negated values in Python's heapq) for the lower half and a min-heap for the upper half. After each insert, rebalance so the lower half has the same size as the upper half or exactly one more element, then read the median from the heap tops.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sorting the prefix after every arrival would cost far too much, and inserting into a sorted list still shifts elements and costs O(n) per step. Since only the middle element(s) matter, keep the values split into two halves using two heaps:
lower: a max-heap (stored as negated values) holding the smaller half.upper: a min-heap holding the larger half.
Two invariants hold after every arrival:
- Ordering: every value in
loweris less than or equal to every value inupper. - Balance:
len(lower) == len(upper)orlen(lower) == len(upper) + 1.
Then the median is read from the tops: for an odd count it is the top of lower; for an even count it is the average of the two tops.
For each new value x:
- Route: if
loweris non-empty andxis greater than the top oflower, push it toupper; otherwise push it tolower. - Rebalance: if
loweris larger by 2, move its top toupper; ifupperis larger thanlower, move its top tolower. - Report: append the median computed from the tops.
Why it is correct
- Routing preserves ordering: a value larger than
max(lower)goes toupper, and otherwise it is at mostmax(lower)and therefore at mostmin(upper), so it fits inlower. - Rebalancing only moves the extreme element of one heap to the other heap, which cannot break ordering.
- Before an insert the size difference is 0 or 1; after it, it lies in {-1, 0, 1, 2}, and a single move restores it to 0 or 1.
- By ordering and balance,
lowerholds exactly the ceil(k/2) smallest values after k arrivals. So the middle value (odd k) is the top oflower, and the two middle values (even k) are the tops oflowerandupper. - Duplicates are separate heap entries, so each is counted.
- Odd medians are converted with
float, and even medians use true division of an integer sum by 2, giving an exactly representable value.
Complexity
- Time: O(n log n), with at most two pushes and one pop per arrival.
- Space: O(n) for the heaps and the output.
Reference solution
import heapq
from typing import List
def running_median_feed(readings: List[int]) -> List[float]:
lower = [] # max-heap of the smaller half (stored negated)
upper = [] # min-heap of the larger half
result = []
for x in readings:
# Route the new value to the correct half.
if lower and x > -lower[0]:
heapq.heappush(upper, x)
else:
heapq.heappush(lower, -x)
# Rebalance: len(lower) == len(upper) or len(upper) + 1.
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
# Read the median from the heap tops.
if len(lower) > len(upper):
result.append(float(-lower[0]))
else:
result.append((-lower[0] + upper[0]) / 2)
return result