Running Median After Each Insertion
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Tests median maintenance using two heaps to efficiently return the running median after each element is added to a growing sequence.
Running Median After Each Insertion
You are given a list of integers representing values that arrive one at a time in order. After each new value is inserted, you must report the median of all values seen so far.
The median is defined as:
- If the current count of values is odd, the median is the middle value when all seen values are sorted.
- If the current count of values is even, the median is the average of the two middle values (as a
float).
Given a list stream of n integers, return a list of n numbers where the i-th element is the median after the first i+1 values have been inserted.
Each element in the result should be either an int (when the count so far is odd) or a float (when the count so far is even). Specifically:
- Odd count → return the exact integer median (type
int). - Even count → return
(left + right) / 2as afloat.
Constraints
1 ≤ len(stream) ≤ 2000-10^6 ≤ stream[i] ≤ 10^6- The output list has exactly
len(stream)elements. - When
nis odd, the median element is anint; whennis even, it is afloat.
Examples
Example 1
Input: running_median([5])
Output: [5]
Example 2
Input: running_median([3, 1, 4, 1, 5])
Output: [3, 2, 3, 2, 3]
Example 3
Input: running_median([10, -10, 0])
Output: [10, 0, 0]
Hints
Hint 1
Think of maintaining two heaps: a max-heap for the lower half and a min-heap for the upper half of the seen values.
Hint 2
After each insertion, rebalance the two heaps so their sizes differ by at most 1. The median is then either the top of the larger heap (odd count) or the average of both tops (even count).
Hint 3
Python's heapq only provides a min-heap; negate values to simulate a max-heap for the lower half.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: Two-Heap Median Maintenance
We maintain two heaps that together store all values seen so far, partitioned at the median:
lower(max-heap): holds the smaller half of values. Implemented as a min-heap of negated values.upper(min-heap): holds the larger half of values.
Invariants after each insertion:
- Every value in
lower≤ every value inupper. len(lower) == len(upper)(even count) orlen(lower) == len(upper) + 1(odd count, lower holds the extra middle element).
With these invariants, the median is:
- Odd count:
-lower[0](the top of the max-heap = the single middle element), returned asint. - Even count:
(-lower[0] + upper[0]) / 2(average of the two middle elements), returned asfloat.
Algorithm per element
- Push the new value into
lower(negate it for max-heap behavior). - If the new top of
lowerexceeds the top ofupper, move it toupperto restore invariant 1. - Rebalance sizes to restore invariant 2: if
loweris more than 1 element larger thanupper, move the top toupper; ifupperis larger thanlower, move its top tolower. - Compute and append the median.
Correctness
The invariants guarantee that at all times the two heaps contain exactly the sorted lower and upper halves. The tops of the heaps are therefore always the one or two middle elements of the sorted sequence, giving the correct median in O(1) after O(log n) heap operations.
Complexity
- Time: O(n log n) — each of the n insertions performs O(log n) heap operations.
- Space: O(n) — all n values are stored across the two heaps.
This is optimal for an online (streaming) setting where values arrive one at a time.
import heapq
from typing import List
def running_median(stream: List[int]) -> List:
lower = [] # max-heap via negation (lower half)
upper = [] # min-heap (upper half)
result = []
for val in stream:
# Push into lower half first
heapq.heappush(lower, -val)
# Ensure every element in lower <= every element in upper
if upper and (-lower[0]) > upper[0]:
heapq.heappush(upper, -heapq.heappop(lower))
# Balance sizes: lower may have at most 1 more element than upper
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
count = len(lower) + len(upper)
if count % 2 == 1:
result.append(int(-lower[0]))
else:
result.append((-lower[0] + upper[0]) / 2)
return result