Running Median from Integer Stream
Heaps, Sorting & SearchAuto-graded · 16 test casesLast updated
Tests ability to maintain order statistics efficiently in a streaming context using heap-based data structures.
Build a system that processes integers one at a time and computes the median of all values seen so far after each operation.
You will receive a sequence of operations:
"add"with argument[x]: insert integerxinto the collection"getMedian"with argument[]: return the current median as a float
The median is defined as:
- For an odd number of elements: the middle value when sorted
- For an even number of elements: the average of the two middle values when sorted
Your function receives two parallel lists: operations (strings) and arguments (lists of integers). Process each operation in order and return a list of results:
- For
"add": appendNoneto the result - For
"getMedian": append the median as afloat - If
"getMedian"is called before any values are added, raise aValueError - If an unknown operation is encountered, raise a
ValueError
Constraints
- 1 ≤ number of operations ≤ 10⁵
- -10⁹ ≤ x ≤ 10⁹
- At least one operation will be present
"getMedian"operations will not exceed the number of preceding"add"operations in valid test cases
Examples
Example 1
Input: running_median(['add', 'add', 'add', 'getMedian', 'add', 'getMedian'], [[2], [3], [1], [], [4], []])
Output: [None, None, None, 2, None, 2.5]
Example 2
Input: running_median(['add', 'getMedian', 'add', 'getMedian'], [[5], [], [5], []])
Output: [None, 5, None, 5]
Hints
Hint 1
The median only depends on the one or two middle elements, not the entire sorted order
Hint 2
Consider maintaining two collections: one for values below the median and one for values above it
Hint 3
Use heap data structures to efficiently track the largest value in the lower half and the smallest value in the upper half
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that computing the median doesn't require maintaining a fully sorted sequence. We only need quick access to the middle element(s). This can be achieved by splitting the data into two halves and tracking their boundary values.
Use two heaps to partition the stream:
- A max-heap holding the smaller half of values (implemented by negating values in Python's min-heap)
- A min-heap holding the larger half of values
Maintain these invariants:
- Every element in the max-heap is less than or equal to every element in the min-heap
- The heaps are balanced: the max-heap contains either the same number of elements as the min-heap, or exactly one more
With these invariants, the median is always at the heap tops:
- If the total count is odd, the max-heap has one extra element and its top is the median
- If the total count is even, the median is the average of both heap tops
Insertion algorithm:
- Decide which heap receives the new value by comparing it to the current max of the smaller half
- After insertion, check if the size difference violates the balance constraint
- If unbalanced, move one element from the larger heap to the smaller one
Why this works:
The insertion preserves ordering because a value only enters the max-heap if it's less than or equal to the current boundary. Rebalancing moves the boundary element (max of lower half or min of upper half), which by definition belongs between the two partitions.
Balance is maintained because before any insertion, the difference in sizes is 0 or 1. One insertion changes this by exactly 1, creating a difference of -1, 0, 1, or 2. A single transfer operation corrects any violation.
Complexity
- Time: O(log n) per
addoperation (heap push and at most one pop+push for rebalancing), O(1) pergetMedianoperation (peek at heap tops) - Space: O(n) to store all inserted values across both heaps
For a sequence of m operations over n accumulated values, total time is O(m log n).
Solution
import heapq
from typing import List, Optional
def running_median(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
max_heap = [] # Stores smaller half (negated for max-heap behavior)
min_heap = [] # Stores larger half
results = []
for op, args in zip(operations, arguments):
if op == "add":
val = args[0]
if not max_heap or val <= -max_heap[0]:
heapq.heappush(max_heap, -val)
else:
heapq.heappush(min_heap, val)
if len(max_heap) > len(min_heap) + 1:
heapq.heappush(min_heap, -heapq.heappop(max_heap))
elif len(min_heap) > len(max_heap):
heapq.heappush(max_heap, -heapq.heappop(min_heap))
results.append(None)
elif op == "getMedian":
if not max_heap:
raise ValueError("getMedian requires at least one inserted value")
if len(max_heap) > len(min_heap):
results.append(float(-max_heap[0]))
else:
results.append((-max_heap[0] + min_heap[0]) / 2.0)
else:
raise ValueError("unknown operation")
return results