792. Track the running median of a latency stream
Dashboards often show the median latency of a model endpoint as requests arrive. Sorting the whole history after every request is too slow, so you need a structure that updates in log time.
Write running_medians(stream). stream is a list of numbers that arrive one at a time. Return a list with the median after each arrival. With an odd count the median is the middle value; with an even count it is the mean of the two middle values. Return every median as a float.
An empty stream returns an empty list.
def running_medians(stream)Example 1
Input: running_medians([5, 15, 1, 3])
Output: [5.0, 10.0, 5.0, 4.0]
Example 2
Input: running_medians([2, 2, 2])
Output: [2.0, 2.0, 2.0]
Constraints
- 0 <=
len(stream)<= 200,000 - Values are ints or floats
Hint 1
Use heapq with negated values for the max heap.
Hint 2
Rebalance after every push.
Hint 3
Decide the median from the heap sizes.
Common mistakes
- Forgetting to negate when popping from the max heap.
- Letting the heaps differ in size by two or more.
- Returning ints for odd counts when floats are required.
Understand the idea
The two heap trick keeps a sorted split without sorting. For [5, 15, 1, 3]: after 5, low = {5}; after 15, high = {15}, median 10; after 1, low = {5, 1}, median 5; after 3, low = {5, 3, 1} is too big, so 5 moves to high = {5, 15}, and the median is (3 + 5) / 2 = 4. The same idea backs streaming p50 monitors. For other percentiles, production systems usually switch to approximate sketches, because exact heaps keep every value in memory.