Streaming Median Query
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests balanced heap design to maintain dynamic order statistics with logarithmic insertions and constant-time median queries.
Streaming Median Query
Build a system that processes a sequence of operations on a numeric stream. The system must support two operations:
- Adding a number to the stream
- Querying the current median of all numbers seen so far
You will receive two parallel lists:
operations: a list of operation names, each either"add_num"or"find_median"arguments: a list of argument lists, wherearguments[i]contains the arguments foroperations[i]
For "add_num" operations, the argument list contains a single integer to add to the stream.
For "find_median" operations, the argument list is empty.
Return a list of results where:
"add_num"operations produceNonein the output"find_median"operations produce the median as a float
Median definition:
- If the count of numbers is odd, return the middle value
- If the count is even, return the arithmetic mean of the two middle values
- If no numbers have been added yet, return
0.0
Constraints
1 <= len(operations) <= 50000operations[i]is either"add_num"or"find_median"-1000000 <= num <= 1000000for any number addedlen(operations) == len(arguments)- Your solution must handle insertions in
O(log n)time and median queries inO(1)time, wherenis the current count of numbers
Examples
Example 1
Input: streaming_median(['add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[1], [2], [], [3], []])
Output: [None, None, 1.5, None, 2]
Example 2
Input: streaming_median(['find_median', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [-5], [], [5], []])
Output: [0, None, -5, None, 0]
Hints
Hint 1
The median only depends on the middle element(s) of sorted order—you don't need to maintain a fully sorted list
Hint 2
Two heaps can partition the stream: one holding the smaller half and one holding the larger half
Hint 3
Python's heapq is a min-heap, but you can simulate a max-heap by negating values
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Streaming Median Query
Approach
The median is determined solely by the middle element(s) when values are in sorted order. Rather than maintaining a complete sorted structure, we can use two heaps to track just the boundaries between the smaller and larger halves of our data.
Data Structure Choice:
We maintain two heaps with complementary roles:
small_half: a max-heap storing the lower portion of values (its root is the largest "small" value)large_half: a min-heap storing the upper portion of values (its root is the smallest "large" value)
Since Python's heapq provides only min-heaps, we simulate a max-heap by storing negated values in small_half.
Invariants:
- Ordering invariant: Every element in
small_halfis less than or equal to every element inlarge_half - Balance invariant:
len(small_half)equals eitherlen(large_half)orlen(large_half) + 1
With these invariants maintained, finding the median becomes trivial:
- Odd total count: the median is the root of
small_half - Even total count: the median is the average of both roots
Insertion Algorithm:
When adding a new value:
- Route it to the appropriate heap based on comparison with
small_half's maximum - Rebalance if the size invariant is violated:
- If
small_halfhas more than one extra element, move its maximum tolarge_half - If
large_halfhas more elements, move its minimum tosmall_half
- If
This ensures both invariants are preserved after each insertion.
Correctness
The ordering invariant is maintained because we explicitly compare each new value against the boundary (the max of small_half) and route it accordingly. The rebalancing transfers only the boundary elements themselves, which by definition satisfy the ordering constraint.
The balance invariant is maintained by the rebalancing step, which ensures small_half is never more than one element larger than large_half, and large_half never exceeds small_half in size.
Together, these invariants guarantee that small_half contains exactly the first ⌈n/2⌉ elements in sorted order, making its root the median or lower-middle element as required.
Complexity
Time:
add_num: O(log n) — at most two heap pushes and one heap popfind_median: O(1) — direct access to heap roots
Space: O(n) — each added value is stored exactly once
Implementation
import heapq
from typing import List, Optional
def streaming_median(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
# Partition: small_half holds smaller values (max-heap via negation)
# large_half holds larger values (min-heap)
small_half = []
large_half = []
results = []
for op, args in zip(operations, arguments):
if op == "add_num":
value = args[0]
# Route value to appropriate half
if not small_half or value <= -small_half[0]:
heapq.heappush(small_half, -value)
else:
heapq.heappush(large_half, value)
# Rebalance: maintain size invariant
if len(small_half) > len(large_half) + 1:
heapq.heappush(large_half, -heapq.heappop(small_half))
elif len(large_half) > len(small_half):
heapq.heappush(small_half, -heapq.heappop(large_half))
results.append(None)
elif op == "find_median":
if not small_half and not large_half:
results.append(0.0)
elif len(small_half) > len(large_half):
results.append(float(-small_half[0]))
else:
results.append((-small_half[0] + large_half[0]) / 2.0)
return results