Running Median of a Sliding Window
Heaps, Sorting & SearchAuto-graded · 15 test casesLast updated
Tests median maintenance by computing the running median after each element is inserted into a growing sequence, using a two-heap approach.
Running Median Stream
You are given a list of integers stream arriving one at a time. After each new integer is consumed, compute the median of all integers seen so far.
The median is defined as:
- If the count of numbers seen so far is odd, the median is the middle element when sorted.
- If the count of numbers seen so far is even, the median is the average of the two middle elements (as a
float).
Return a list of medians (one per element), where each median is either an int (when the running count is odd) or a float (when the running count is even).
Note: Return the median as an int when it is a whole number resulting from an odd-length prefix, and as a float (e.g. 4.5) when it results from averaging two middle elements — even if that average is a whole number (e.g. return 4.0, not 4).
Constraints
1 <= len(stream) <= 2000-10^6 <= stream[i] <= 10^6- After an odd number of elements, return the median as an
int. - After an even number of elements, return the median as a
float.
Examples
Example 1
Input: running_median([3, 1, 4, 1, 5])
Output: [3, 2, 3, 2, 3]
Example 2
Input: running_median([7])
Output: [7]
Example 3
Input: running_median([5, 3])
Output: [5, 4]
Hints
Hint 1
Maintain two heaps: a max-heap of the lower half and a min-heap of the upper half, keeping their sizes balanced so they differ by at most 1.
Hint 2
After each insertion, rebalance the heaps so the size difference stays ≤ 1. The median is either the top of the larger heap (odd count) or the average of both tops (even count).
Hint 3
Python's heapq is 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: Two-Heap Median Maintenance
Idea
We maintain two heaps at all times:
lower: a max-heap holding the smaller half of the numbers seen so far (implemented as a min-heap of negated values).upper: a min-heap holding the larger half of the numbers seen so far.
Invariants after each insertion:
- Every element in
lower≤ every element inupper. len(lower)is either equal tolen(upper)(even total count) or exactly one more (odd total count).
With these invariants, reading the median is O(1):
- Odd count:
lowerhas one extra element; its maximum (-lower[0]) is the median → return asint. - Even count: both heaps are the same size; the median is the average of their tops → return as
float.
Insertion Steps
- Push
numontolower(as-num). - Order fix: if
-lower[0] > upper[0](the largest of the lower half exceeds the smallest of the upper half), pop fromlowerand push toupper. - Size fix: if
lowergrew too large (len(lower) > len(upper) + 1), move one element up; ifupperis larger thanlower, move one element down.
Correctness
The two invariants together ensure that at any moment the heaps form a sorted partition of the stream at the median boundary. The rebalancing steps restore both invariants in O(log n) time per insertion.
Complexity
| Time | Space | |
|---|---|---|
| Per element | O(log n) | — |
| Total | O(n log n) | O(n) |
Reference Solution
import heapq
from typing import List
def running_median(stream: List[int]) -> list:
# max-heap for lower half (store negated values)
lower = [] # max-heap via negation
# min-heap for upper half
upper = [] # min-heap
result = []
for num in stream:
# Push to lower half first
heapq.heappush(lower, -num)
# Balance: largest of lower must be <= smallest of upper
if upper and (-lower[0]) > upper[0]:
val = -heapq.heappop(lower)
heapq.heappush(upper, val)
# Rebalance sizes so they differ by at most 1
if len(lower) > len(upper) + 1:
val = -heapq.heappop(lower)
heapq.heappush(upper, val)
elif len(upper) > len(lower):
val = heapq.heappop(upper)
heapq.heappush(lower, -val)
# Compute median
if len(lower) == len(upper):
# even count -> float
result.append((-lower[0] + upper[0]) / 2.0)
else:
# odd count: lower has one more -> int
result.append(-lower[0])
return result