Running Median via Dual-Heap Simulation
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests whether a candidate can maintain a live median over an integer stream in O(log n) per insert using two heaps balanced around the midpoint.
Running Median via Dual-Heap Simulation
You are given a sequence of operations that build up a collection of integers one value at a time and periodically ask for the current median. Simulate those operations and collect every median result.
Definitions
Given a collection of numbers sorted in non-decreasing order:
- Odd size: the median is the single element at the center position.
- Even size: the median is the arithmetic mean of the two elements nearest the center.
Input Format
You receive two lists of equal length:
operations— a list of strings, each either"add"or"median".arguments— a list of lists. For an"add"operation,arguments[i]contains exactly one integer, the value to insert. For a"median"operation,arguments[i]is an empty list.
Process the operations in order, starting from an empty collection.
Output Format
Return a list with one entry per operation:
- For every
"add"operation, the corresponding entry isNone. - For every
"median"operation, the corresponding entry is the median of all values inserted so far, as afloat.
If an operation string is neither "add" nor "median", raise a ValueError.
Constraints
- Integer values supplied to
"add"are within the range of 32-bit signed integers and may be negative or repeated. - The total number of operations is at most 10^5.
"median"is never the first operation; at least one"add"always precedes it.- The returned median must be arithmetically exact. When the collection size is even, return the true average of the two central values (e.g.,
2.5, not2). "add"and"median"calls may be freely interleaved in any order.- Your solution must handle each
"add"in roughly O(log n) time and each"median"in O(1) time. A full re-sort on every query is too slow for the given input size.
Examples
Example 1
Input: median_tracker(['add', 'median', 'add', 'median', 'add', 'median', 'add', 'median'], [[1], [], [3], [], [2], [], [10], []])
Output: [None, 1, None, 2, None, 2, None, 2.5]
Example 2
Input: median_tracker(['add', 'add', 'add', 'add', 'median', 'median'], [[-5], [-5], [0], [10], [], [], []])
Output: [None, None, None, None, -2.5, -2.5]
Hints
Hint 1
Think about what information you actually need to compute the median — you only care about the one or two values at the center of the sorted order, not the entire sorted list. What data structures give you instant access to a maximum or a minimum?
Hint 2
Two heaps work well here: one holding the smaller half of the values, one holding the larger half. If you keep their sizes within one of each other at all times, the tops of the two heaps are exactly the values you need for the median.
Hint 3
Python's heapq is a min-heap only. To simulate a max-heap for the lower half, store each value negated — push -x instead of x, and negate again when you peek or pop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
To compute the median you only ever need the one or two values sitting at the center of the sorted collection — not the full sorted list. Concretely, you need fast access to:
- the largest value in the lower half, and
- the smallest value in the upper half.
A max-heap and a min-heap give exactly those in O(1).
Two-heap structure
lower— a max-heap over the smaller half. Python only ships a min-heap (heapq), so every value is stored negated: pushing-xand peeking at-lower[0]simulates a max-heap.upper— a standard min-heap over the larger half.
Two invariants are enforced after every insert:
- Ordering: every element in
lower≤ every element inupper. - Balance:
len(lower)equalslen(upper)orlen(upper) + 1. The lower half may carry one extra element; the upper half never may.
Given those invariants, the median falls out immediately:
- Odd total (
loweris one larger): median is-lower[0]. - Even total (equal sizes): median is
(-lower[0] + upper[0]) / 2.0.
How insertion works
- Route the new value. If
loweris empty, or the value does not exceed the current lower-half maximum, push it intolower. Otherwise push it intoupper. This preserves the ordering invariant. - Rebalance. One push shifts one heap's size by 1. A single conditional transfer restores the balance invariant:
- If
lowernow holds two more elements thanupper, poplower's max and push it ontoupper. - If
upperis larger thanlower, popupper's min and push it ontolower.
- If
At most one element moves per insert.
Why the invariants hold
Ordering after routing. A value routed to lower is ≤ the old max of lower, which by the prior ordering invariant is ≤ every element in upper. A value routed to upper is strictly greater than that max, so it belongs there.
Ordering after rebalancing. Only the boundary element of a heap ever crosses: the max of lower moves to upper, or the min of upper moves to lower. Moving a boundary element cannot violate the ordering invariant.
Median correctness. Because ordering holds, lower contains exactly the smallest len(lower) elements of the multiset. With an odd total n = 2k + 1, lower holds k + 1 elements and its max is the (k+1)-th smallest — the exact median. With an even total n = 2k, the k-th and (k+1)-th smallest sit at the tops of lower and upper respectively.
Exact arithmetic. Inputs fit in 32-bit integers, so their sum fits easily in a 64-bit float's 53-bit mantissa. Dividing by 2.0 is also exact for values of this magnitude, so results like 2.5 or -0.5 are represented exactly.
Edge cases
- Single element:
loweris empty, so the value always routes there. The median isfloatof that value. - Duplicates: the
<=comparison sends ties tolower; rebalancing corrects any resulting skew. For example,[5, 5, 5, 5]yields median5.0. - Negative values: negation works for any Python integer, which has no overflow. For example,
[-3, 2]gives-0.5. - Monotone streams: rebalancing triggers on every insert in a strictly increasing or decreasing stream, but each rebalance is still O(log n).
- Repeated
mediancalls between inserts:medianis read-only and returns the same value each time until the nextadd.
Complexity
add: O(log n) — at most two pushes and one pop.median: O(1) — one or two heap peeks.- Overall for m operations: O(m log m) time, O(n) space for stored elements.
Reference solution
import heapq
from typing import List, Optional
def median_tracker(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
# lower is a max-heap over the smaller half, implemented via negation.
# upper is a min-heap over the larger half.
# Invariants maintained after every insert:
# 1. Ordering: every value in lower <= every value in upper.
# 2. Balance: len(lower) == len(upper) or len(lower) == len(upper) + 1.
lower = [] # max-heap (negated values)
upper = [] # min-heap
results = []
for op, arg in zip(operations, arguments):
if op == "add":
value = arg[0]
# Route: values <= current lower-half max go left; rest go right.
if not lower or value <= -lower[0]:
heapq.heappush(lower, -value)
else:
heapq.heappush(upper, value)
# Rebalance so the size difference is at most 1, with lower >= upper.
if len(lower) > len(upper) + 1:
# Lower has two more elements than upper; move its max across.
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
# Upper is larger; move its min across.
heapq.heappush(lower, -heapq.heappop(upper))
results.append(None)
elif op == "median":
if len(lower) > len(upper):
# Odd total count: the top of the lower heap is the middle element.
results.append(float(-lower[0]))
else:
# Even total count: average the two central elements.
results.append((-lower[0] + upper[0]) / 2.0)
else:
raise ValueError(f"unrecognized operation: {op!r}")
return results