Stream Median Tracker
Heaps, Sorting & SearchAuto-graded · 14 test casesLast updated
Process a series of dynamic data stream queries to compute the median on demand using heap-based structures.
You are asked to process a sequence of operations on a dynamic integer stream structure.
The operations are given as two parallel lists, operations and arguments:
"MedianFinder": Initializes (or resets) the internal state. The corresponding argument is[]. The return value for this command should beNone."add_num": Receives a single integer passed inarguments[i](e.g.,[x]) and inserts it into the data stream. The return value for this command should beNone."find_median": Calculates the current median of all integers inserted so far. The corresponding argument is[]. The return value should be afloat. If the count of inserted numbers is odd, the median is the middle value. If the count is even, the median is the arithmetic mean of the two central values.
Your function should return a list containing the output of each operation in order.
Constraints
- Total calls to
add_numandfind_medianwill not exceed $5 \times 10^4$. - Each stream value lies within the range $[-10^5, 10^5]$.
find_medianwill only be called after at least one number has been added to the stream.
Edge Cases
- Stream contains negative numbers.
- Consecutive identical numbers are added.
- Alternate queries on odd and even numbers of elements.
Examples
Example 1
Input: median_finder(['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: median_finder(['MedianFinder', 'add_num', 'add_num', 'add_num', 'find_median'], [[], [5], [5], [5], []])
Output: [None, None, None, None, 5]
Hints
Hint 1
To get O(log N) insertion and O(1) median retrieval, split the data into two halves using two heaps.
Hint 2
Use a max-heap for the smaller half of the numbers and a min-heap for the larger half.
Hint 3
Keep the sizes of both heaps balanced so that the max-heap has either equal size or exactly one more element than the min-heap.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maintain the median of an incoming data stream efficiently, sorting every time a median is requested ($O(N \log N)$) or inserting into a sorted list ($O(N)$ insertion) is too slow.
Instead, we split our data into two equal (or nearly equal) halves using two heaps:
lower: A max-heap containing the smaller half of elements. In Python,heapqis a min-heap, so we store negated values here. The maximum value of this half will always be at-lower[0].upper: A min-heap containing the larger half of elements. The minimum value of this half is atupper[0].
Heap Invariants
- Order Invariant: Every element in
loweris less than or equal to every element inupper. - Size Invariant:
len(lower)is either equal tolen(upper)orlen(upper) + 1.
Operation Logic
add_num(num):- Push
numintolowerifnum <= max(lower)(i.e.,num <= -lower[0]), otherwise push intoupper. - Rebalance: If
len(lower) > len(upper) + 1, move the max oflowertoupper. Iflen(upper) > len(lower), move the min ofuppertolower.
- Push
find_median():- If
len(lower) > len(upper), the median is simply-lower[0]. - If
len(lower) == len(upper), the median is(-lower[0] + upper[0]) / 2.0.
- If
Complexity Analysis
add_num: $O(\log N)$ per addition due to heap push and pop operations.find_median: $O(1)$ time complexity as it only inspects the roots of the two heaps.- Overall Time Complexity: $O(M \log M)$ for $M$ operations.
- Space Complexity: $O(N)$ to store $N$ elements across the two heaps, plus $O(M)$ space for the results array.
Python Reference Solution
import heapq
from typing import List, Optional
def median_finder(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
lower = [] # Max-heap for lower half of numbers (store inverted values)
upper = [] # Min-heap for upper half of numbers
results: List[Optional[float]] = []
for op, args in zip(operations, arguments):
if op == "MedianFinder":
lower.clear()
upper.clear()
results.append(None)
elif op == "add_num":
num = args[0]
# Step 1: Push to appropriate heap
if not lower or num <= -lower[0]:
heapq.heappush(lower, -num)
else:
heapq.heappush(upper, num)
# Step 2: Rebalance heaps to satisfy size invariant
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}")
return results