Running Median Tracker with Dual-Heap Design
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests the ability to maintain an efficient two-heap structure that yields the current median of a growing integer stream in O(log n) per insertion and O(1) per query.
Running Median Tracker
You are building a statistics module for a real-time data pipeline. Integers arrive one at a time, and after each batch of inserts, the pipeline queries the current median of every integer received so far.
Design a class RunningMedian with the following interface:
RunningMedian()— sets up the internal state (no return value).add_num(val)— records one new integer from the stream (no return value).find_median()— returns the median of all integers recorded so far, as afloat.
Median definition
- If the total count of recorded integers is odd, the median is the single middle value when all values are placed in sorted order.
- If the total count is even, the median is the arithmetic mean of the two values closest to the middle.
Judge interface
The judge drives the class through two parallel lists:
operations— a list of operation name strings:"MedianFinder","add_num", or"find_median".arguments— a list of argument lists, one per operation."MedianFinder"and"find_median"receive[];"add_num"receives[val].
Implement the function:
def running_median_tracker(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
It must return one output per operation:
Nonefor"MedianFinder"and"add_num".- A
floatfor"find_median".
Constraints
- The total number of operations is between 1 and 100,000.
add_numis called at most 50,000 times.find_medianis called at most 50,000 times.- Every integer value passed to
add_numis in the range[-10^5, 10^5]. find_medianis never called before at least oneadd_numhas been made.- An unknown operation name should raise
ValueError.
Examples
Example 1
Input: running_median_tracker(['MedianFinder', 'add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [1], [2], [], [3], []])
Output: [None, None, None, 1.5, None, 2]
Example 2
Input: running_median_tracker(['MedianFinder', 'add_num', 'add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [5], [5], [5], [], [5], []])
Output: [None, None, None, None, 5, None, 5]
Hints
Hint 1
Think about what you actually need to know to answer a median query instantly — you only care about the one or two values nearest the centre of the sorted sequence, not the full order.
Hint 2
Try splitting the recorded values into two groups: a lower half and an upper half. If you can read the maximum of the lower half and the minimum of the upper half in O(1), you have everything you need for the median.
Hint 3
Python's heapq only gives a min-heap. You can simulate a max-heap on the lower half by storing each value negated, so the smallest stored number corresponds to the largest real value.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
A full sorted copy of the stream gives the median trivially, but inserting into a sorted list costs O(n) due to shifting. The key insight is that a median query only ever looks at the middle one or two elements — never the rest. That means you only need fast access to those boundary values.
Two-heap partition
Maintain two heaps that together hold all values seen so far:
lower— a max-heap containing the smaller half of the values. Its root is the largest value in that half.upper— a min-heap containing the larger half of the values. Its root is the smallest value in that half.
Two invariants are kept after every insert:
- Order: every value in
lower≤ every value inupper. - Size balance:
len(lower) == len(upper)orlen(lower) == len(upper) + 1. The lower heap is allowed to carry the single extra element when the total count is odd.
With both invariants holding, find_median is O(1):
- Odd total → the median is the root of
lower(the largest of the smaller half). - Even total → the median is the average of the two roots.
Python's heapq is a min-heap only. Simulating a max-heap on lower is done by negating every stored value, so -lower[0] recovers the actual maximum.
Insertion steps
- Route the new value. If
loweris empty or the value is ≤ the current max oflower, push it ontolower; otherwise push it ontoupper. - Rebalance if needed. After routing, one heap may be out of balance by more than one element. Move the boundary root across: if
lowergrew too large, pop its max and push it ontoupper; ifuppergrew larger thanlower, pop its min and push it ontolower. At most one such move is ever needed per insert.
Why the invariants hold
Order is preserved by routing. Before the insert, max(lower) ≤ min(upper). A new value that is ≤ max(lower) belongs in the lower half; a value that is larger belongs in the upper half. Either way it cannot violate the cross-heap order.
Order is preserved by rebalancing. Moving max(lower) to upper is safe because that element is ≤ everything already in upper — it was the boundary. Moving min(upper) to lower is safe for the symmetric reason.
Size balance means the median lives at the roots. With n total elements and lower holding ⌈n/2⌉ of them, the sorted-order median position(s) are exactly the root(s) of the two heaps.
Edge cases
- Single element: it lands in
lower; sizes are 1 and 0;find_medianreturns that element as a float. - Duplicates / all equal: equal values route to
lowerfirst. Rebalancing copies them toupperas needed. Both roots are equal, so the median is that value regardless of parity. - Negative values: handled naturally by the negation convention on
lower. - Return type: always a
float. Usefloat(...)for the odd case and/ 2.0for the even case to avoid integer division.
Complexity
| Operation | Time | Notes |
|---|---|---|
add_num | O(log n) | at most two heap pushes and one pop |
find_median | O(1) | reads two roots |
| Space | O(n) | all values are stored across the two heaps |
For up to 100,000 total operations the overall cost is O(n log n), well within typical time limits.
Reference solution
import heapq
from typing import List, Optional
def running_median_tracker(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
# lower: max-heap of the smaller half (values stored negated for heapq)
# upper: min-heap of the larger half
lower: List[int] = []
upper: List[int] = []
results: List[Optional[float]] = []
for op, arg in zip(operations, arguments):
if op == "MedianFinder":
results.append(None)
elif op == "add_num":
val = arg[0]
# Route: goes to lower if it belongs to the smaller half, else upper
if not lower or val <= -lower[0]:
heapq.heappush(lower, -val)
else:
heapq.heappush(upper, val)
# Rebalance: lower may hold at most one extra element
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
results.append(None)
elif op == "find_median":
if len(lower) > len(upper):
results.append(float(-lower[0]))
else:
results.append((-lower[0] + upper[0]) / 2.0)
else:
raise ValueError(f"unknown operation: {op!r}")
return results