Running Median Over a Live Integer Feed
Data Structure DesignAuto-graded · 16 test casesLast updated
Tests whether a candidate can design a two-heap structure that inserts integers and queries the running median in better than O(N) time per operation.
Problem
You are building a component that processes a live feed of integers one at a time. At any point the system must be able to report the current median of every integer received so far.
Your implementation is driven by two parallel lists of equal length: a list of operation names and a list of argument lists. Supported operations:
"add_num"— records one integer. ReturnsNone."find_median"— returns the current median as afloat. Its argument list is always empty ([]).
Any unrecognized operation name should raise a ValueError.
Median Definition
Sort all integers recorded up to this point.
- If the count is odd, the median is the single middle value.
- If the count is even, the median is the arithmetic mean of the two middle values.
Always return a float (e.g. 2.0, not 2).
Input and Output
operations: a list of operation name strings.arguments: a list of argument lists, one per operation.
Return a single list where each entry is the result of the corresponding operation (None for "add_num", a float for "find_median").
Constraints
- Both
"add_num"and"find_median"must run in better than O(N) time, where N is the total number of integers added so far. - All integers are in the range
[-10^6, 10^6]. "find_median"is never called before at least one"add_num".- The feed may contain duplicate integers.
1 <= len(operations) <= 10^4
Examples
Example 1
Input: median_finder(['add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[1], [2], [], [3], []])
Output: [None, None, 1.5, None, 2]
Hints
Hint 1
Think about splitting the numbers seen so far into two halves — a lower half and an upper half — so the median always sits right at the boundary between them. What data structures let you peek at the largest element of one group and the smallest element of the other in O(1)?
Hint 2
Python's heapq only provides a min-heap. You can simulate a max-heap for the lower half by pushing negated values: the minimum of the negated numbers is the maximum of the originals.
Hint 3
After every add_num, check two conditions: (1) the largest element in the lower half must be ≤ the smallest element in the upper half, and (2) the sizes must satisfy len(lower) == len(upper) or len(lower) == len(upper) + 1. At most one element swap between the heap tops restores both conditions.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The median only depends on the element(s) at the boundary between the lower half and the upper half of the sorted sequence. We never need the full sorted order — just fast access to those boundary values.
Data structure
Keep two heaps:
lower— a max-heap over the smaller half. Python only provides a min-heap, so store every value negated. The true maximum is retrieved as-lower[0].upper— a min-heap over the larger half.upper[0]is its smallest element.
Two invariants are maintained after every operation:
- Ordering:
-lower[0] <= upper[0]— the largest element of the lower half never exceeds the smallest element of the upper half. - Balance:
len(lower) == len(upper)orlen(lower) == len(upper) + 1— the lower half may hold at most one extra element to carry the median when the total count is odd.
Insertion (add_num)
- Route the new number. If
loweris empty, or the number is ≤ the current max oflower, push it ontolower. Otherwise push it ontoupper. This keeps the ordering invariant intact. - Rebalance. One push shifts the size difference by ±1.
- If
lowernow has two more elements thanupper, poplower's maximum and push it ontoupper. - If
upperis now strictly larger thanlower, popupper's minimum and push it ontolower. Both transfers move a boundary element, so the ordering invariant stays intact.
- If
Reading the median (find_median)
- Odd total (
len(lower) > len(upper)): return-lower[0]as a float. - Even total (
len(lower) == len(upper)): return(-lower[0] + upper[0]) / 2.0.
Why this is correct
The sorted sequence is conceptually lower (ascending) concatenated with upper (ascending). The balance invariant guarantees lower holds exactly ⌈N/2⌉ elements. Its maximum is therefore the middle element for odd N, and one of the two middle elements for even N.
Routing ensures a new element lands in the right half. Rebalancing then restores the size invariant while keeping both halves ordered relative to each other, because we always move a boundary element.
Complexity
| Operation | Time | Space |
|---|---|---|
add_num | O(log N) | — |
find_median | O(1) | — |
| Overall space | — | O(N) |
This satisfies the "better than O(N) per operation" requirement. A sorted list with bisect.insort finds the insertion point in O(log N) but then shifts elements in O(N).
Edge cases
- Single element:
lowerhas one entry,upperis empty. The odd-count branch returns-lower[0]without touchingupper. - Duplicates: the
<=comparison sends ties tolower. After rebalancing they may be split across both heaps, which is fine because the ordering invariant uses ≤, not <. - Negative numbers: negating for the max-heap works correctly for negative inputs. All values fit within ±10⁶ so there is no overflow concern.
- Return type: always return a
float. The reference usesfloat(...)for the odd branch and/ 2.0for the even branch to guarantee this.
Reference solution
import heapq
from typing import List, Optional
def median_finder(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
# lower: max-heap (stored as negated values) — holds the smaller half
# upper: min-heap — holds the larger half
# Invariants:
# 1. -lower[0] <= upper[0] (every element in lower <= every element in upper)
# 2. len(lower) == len(upper) or len(lower) == len(upper) + 1
lower = [] # max-heap via negation
upper = [] # min-heap
results = []
for operation, args in zip(operations, arguments):
if operation == "add_num":
num = args[0]
# Route to the correct half
if not lower or num <= -lower[0]:
heapq.heappush(lower, -num)
else:
heapq.heappush(upper, num)
# Restore the balance invariant
if len(lower) > len(upper) + 1:
# lower has too many: move its maximum to upper
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
# upper has too many: move its minimum to lower
heapq.heappush(lower, -heapq.heappop(upper))
results.append(None)
elif operation == "find_median":
if len(lower) > len(upper):
# Odd total: the extra element in lower is the median
results.append(float(-lower[0]))
else:
# Even total: average the two middle elements
results.append((-lower[0] + upper[0]) / 2.0)
else:
raise ValueError(f"Unknown operation: {operation}")
return results