Running Median of an Integer Stream
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement a streaming median tracker exposed through the driver function:
def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
Numbers arrive sequentially, interleaved with median lookups. Each index i pairs an operation name operations[i] with its argument list arguments[i]:
"addNum"with[x]: record integerxin the multiset of observed values and appendNoneto the output list."findMedian"with[]: compute the median of every integer recorded up to this point and append it as afloat(if no integers have been recorded yet, appendNone).
How the median is defined when all k recorded integers are arranged in non-decreasing order:
- Odd
k: the single element at indexk // 2. - Even
k(k > 0): the exact floating-point mean(a + b) / 2.0of the two central elementsaandb.
Your data structure should process each "addNum" call in O(log n) time and answer each "findMedian" call in O(1) (or O(log n)) time, where n is the number of values inserted so far.
Examples
Example 1
Input:
operations = ["addNum", "addNum", "findMedian", "addNum", "findMedian"]
arguments = [[6], [10], [], [2], []]
Output:
[None, None, 8.0, None, 6.0]
Walk-through: After inserting 6 and 10, the sorted values are [6, 10], so "findMedian" returns (6 + 10) / 2.0 = 8.0. Inserting 2 updates the sorted values to [2, 6, 10], whose middle value is 6.0.
Example 2
Input:
operations = ["addNum", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
arguments = [[-4], [-9], [-5], [], [2], []]
Output:
[None, None, None, -5.0, None, -4.5]
Walk-through: After the first three insertions, the sorted stream is [-9, -5, -4], giving median -5.0. Appending 2 yields [-9, -5, -4, 2], and averaging the two central elements -5 and -4 gives (-5 + -4) / 2.0 = -4.5.
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every
operations[i]is either"addNum"(witharguments[i] = [x]) or"findMedian"(witharguments[i] = []). - Incoming values
xare integers that may be negative, zero, or positive, and duplicate values are retained with full multiplicity.
Step-by-step walkthrough
Understand the problem and median rules
Integers arrive one at a time in a live stream, and at any point we can be asked for the median of everything observed so far:
- Odd count: if we sorted all recorded numbers, the median is the single central value (for
[2, 6, 10], the median is6.0). - Even count: the median is the arithmetic mean of the two central values (for
[6, 10], the median is(6 + 10) / 2.0 = 8.0).
Values may be negative and may repeat (
[5, 5, 1, 1]has sorted order[1, 1, 5, 5]and median(1 + 5) / 2.0 = 3.0).The driver function
median_stream(operations, arguments)pairs"addNum"with[x](appendingNone) and"findMedian"with[](appending thefloatmedian, orNoneif no numbers have been inserted yet). With up to10^5operations, we wantO(log n)per insertion andO(1)per query.- Odd count: if we sorted all recorded numbers, the median is the single central value (for
Why sorting or keeping a sorted list is too slow
Two straightforward list ideas both hit a bottleneck when 50,000 insertions are interleaved with 50,000 queries:
- Append in
O(1), sort on everyfindMedian: each sort costsO(n log n), adding up to billions of comparisons across 50,000 queries. - Maintain a sorted list with binary search (
bisect.insort): reading the middle index isO(1), but inserting into the middle of a Python list shifts up tonelements in memory, makingaddNumO(n).
Notice why both do wasted work: we never query arbitrary ranks like the 10th or 500th smallest element — we only ever inspect the boundary right at the center of the sorted order!
- Append in
Key idea: split the stream into two heaps
Cut the sorted numbers cleanly in half at the median:
lowholds the smaller half in a max-heap (a tree-based priority queue givingO(1)access to its largest value andO(log n)insertion/removal).highholds the larger half in a min-heap (givingO(1)access to its smallest value andO(log n)insertion/removal).
Sorted view: [ 2, 4, 6 | 9, 10 ] \_______/ \___/ low high (max-heap) (min-heap) top = 6 top = 9We maintain two invariants after every
addNum:- Order invariant: every number in
lowis<=every number inhigh(equivalently,max(low) <= min(high)). - Size invariant:
lowhas either the exact same size ashigh(even total count) or one more element thanhigh(odd total count):len(low) == len(high)orlen(low) == len(high) + 1.
When both invariants hold, the center of the stream always sits right at
low[0]andhigh[0]! Because Python'sheapqmodule implements a min-heap, we simulate a max-heap inlowby storing negated numbers (-x): the smallest negated entryself.low[0]corresponds to the largest original value-self.low[0].Insert a number and rebalance the two halves
Each
add_num(x)runs in two short phases:- Pick the right heap (preserve Order): If
lowis empty orx <= -self.low[0],xbelongs in the smaller half, so push-xintolow. Otherwisexexceeds everything inlow, so pushxintohigh. - Restore balance if needed (preserve Size): One insertion changes a heap's size by only
1, so at most one transfer across the center restores the size invariant:- If
len(low) > len(high) + 1, poplow's largest value (-heapq.heappop(self.low)) and push it intohigh. - If
len(high) > len(low), pophigh's smallest value (heapq.heappop(self.high)) and push its negation intolow.
- If
class MedianFinder: def __init__(self) -> None: # low: max-heap of the smaller half, stored negated because heapq is a min-heap. # Example: real values {1, 2} are stored as [-2, -1], so -self.low[0] == 2 (largest of low). self.low: List[int] = [] # high: min-heap of the larger half, stored as-is. # Example: real values {3, 4} are stored as [3, 4], so self.high[0] == 3 (smallest of high). self.high: List[int] = [] def add_num(self, x: int) -> None: # Phase 1: Place x into the half it belongs to so max(low) <= min(high) stays true. if not self.low or x <= -self.low[0]: heapq.heappush(self.low, -x) else: heapq.heappush(self.high, x) # Phase 2: Rebalance sizes so len(low) is always equal to len(high) or len(high) + 1. if len(self.low) > len(self.high) + 1: largest_in_low = -heapq.heappop(self.low) heapq.heappush(self.high, largest_in_low) elif len(self.high) > len(self.low): smallest_in_high = heapq.heappop(self.high) heapq.heappush(self.low, -smallest_in_high)- Pick the right heap (preserve Order): If
Read the median in O(1) time
Because our Size invariant guarantees
len(low)is eitherlen(high) + 1orlen(high),find_mediannever mutates either heap — it simply peeks at index0:- When
len(low) > len(high), the total count is odd, andlowholds the extra middle value-self.low[0]. - Otherwise
len(low) == len(high), so the total count is even, and we average-self.low[0]andself.high[0]with true float division/ 2.0(never floor division// 2, which would round-4.5down to-5).
def find_median(self) -> Optional[float]: if not self.low: return None max_of_low = -self.low[0] # Odd total count: low holds the 1 extra middle element. if len(self.low) > len(self.high): return float(max_of_low) # Even total count: average the two middle elements with true float division '/'. min_of_high = self.high[0] return (max_of_low + min_of_high) / 2.0- When
Dispatch operations and trace Example 2
The driver
median_streamcreates oneMedianFinderinstance and steps throughoperationsandarguments.def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]: finder = MedianFinder() results: List[Optional[float]] = [] # Process each stream event in arrival order. for op, args in zip(operations, arguments): if op == "addNum": finder.add_num(args[0]) results.append(None) elif op == "findMedian": results.append(finder.find_median()) else: raise ValueError(f"Unknown operation: {op}") return resultsLet's trace Example 2 (
addNum(-4),addNum(-9),addNum(-5),findMedian(),addNum(2),findMedian()), showing the real values in each half alongside whatself.lowstores negated:1. addNum(-4): low is empty -> push to low low real: {-4} (stored as [4]), high: {} sizes 1, 0 (ok) 2. addNum(-9): -9 <= max(low) (-4) -> push to low -> low real: {-9, -4}, sizes 2, 0 (low too big!) rebalance: pop max(low) = -4, push to high low real: {-9} (stored as [9]), high: [-4] sizes 1, 1 (ok) 3. addNum(-5): -5 > max(low) (-9) -> push to high -> high: [-5, -4], sizes 1, 2 (high too big!) rebalance: pop min(high) = -5, push to low low real: {-9, -5} (stored as [5, 9]), high: [-4] sizes 2, 1 (ok) 4. findMedian(): len(low) > len(high) -> max(low) = -self.low[0] = -5.0 5. addNum(2): 2 > max(low) (-5) -> push to high low real: {-9, -5} (stored as [5, 9]), high: [-4, 2] sizes 2, 2 (ok) 6. findMedian(): len(low) == len(high) -> (-5 + -4) / 2.0 = -4.5The returned list is
[None, None, None, -5.0, None, -4.5].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq class MedianFinder: def __init__(self) -> None: # low: max-heap of the smaller half, stored negated because heapq is a min-heap. # Example: real values {1, 2} are stored as [-2, -1], so -self.low[0] == 2 (largest of low). self.low: List[int] = [] # high: min-heap of the larger half, stored as-is. # Example: real values {3, 4} are stored as [3, 4], so self.high[0] == 3 (smallest of high). self.high: List[int] = [] def add_num(self, x: int) -> None: # Phase 1: Place x into the half it belongs to so max(low) <= min(high) stays true. if not self.low or x <= -self.low[0]: heapq.heappush(self.low, -x) else: heapq.heappush(self.high, x) # Phase 2: Rebalance sizes so len(low) is always equal to len(high) or len(high) + 1. if len(self.low) > len(self.high) + 1: largest_in_low = -heapq.heappop(self.low) heapq.heappush(self.high, largest_in_low) elif len(self.high) > len(self.low): smallest_in_high = heapq.heappop(self.high) heapq.heappush(self.low, -smallest_in_high) def find_median(self) -> Optional[float]: if not self.low: return None max_of_low = -self.low[0] # Odd total count: low holds the 1 extra middle element. if len(self.low) > len(self.high): return float(max_of_low) # Even total count: average the two middle elements with true float division '/'. min_of_high = self.high[0] return (max_of_low + min_of_high) / 2.0 def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]: finder = MedianFinder() results: List[Optional[float]] = [] # Process each stream event in arrival order. for op, args in zip(operations, arguments): if op == "addNum": finder.add_num(args[0]) results.append(None) elif op == "findMedian": results.append(finder.find_median()) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a growing crowd split into two balanced teams on either side of a center line: everyone on the left team is shorter than (or equal to) everyone on the right team. Neither team needs to stand in full sorted order — as long as the tallest person on the left team and the shortest person on the right team stand right at the center line, you can read the median height instantly! We model those two teams with two heaps — tree-based priority queues that expose their extreme element at index 0 in O(1) time while supporting pushes and pops in O(log n) time: a max-heap low (keeping the largest value of the smaller half on top) and a min-heap high (keeping the smallest value of the larger half on top).
Naive list-based designs waste effort ordering elements far away from the middle. Appending to an unsorted list and sorting on every findMedian costs O(n log n) per query, while inserting into a sorted list (bisect.insort) shifts up to n items in memory, costing O(n) per addNum. Across 50,000 insertions and 50,000 lookups, both list approaches degrade to quadratic total work, whereas two heaps finish each addNum in O(log n) time and each findMedian in O(1) time.
Walk through Example 1 where 6, 10, and 2 arrive:
addNum(6):lowis empty, so6goes intolow. Nowlow = {6},high = {}, and the median would be6.0.addNum(10):10 > max(low)(6), so10goes intohigh. Nowlow = {6}(size 1) andhigh = {10}(size 1) are already balanced, sofindMedian()averages the two tops:(6 + 10) / 2.0 = 8.0.addNum(2):2 <= max(low)(6), so2goes intolow, makinglow = {2, 6}(size 2, top6) andhigh = {10}(size 1, top10). Sincelen(low) == len(high) + 1, no rebalance is needed, andfindMedian()returnsmax(low) = 6.0. (Whenever an insertion pushes a heap two ahead on the left or one ahead on the right, a single pop-and-push across the boundary restores balance.)
Complexity
Let n be the number of integers inserted so far and m be the total number of operations.
addNumtime — O(log n): We comparexagainstlow's top in O(1), run one heap push in O(log n), and if the heap sizes violate the balance rule, run one heap pop and one heap push in O(log n). At most three heap operations execute per insertion.findMediantime — O(1): We readself.low[0](plusself.high[0]when the count is even) without mutating either heap. Over m total operations, the full run takes O(m log m) time.- Space — O(n): Each inserted integer resides in either
self.loworself.highonce, storing n integers in total.
Edge cases
- Single element:
lowholds that element andhighis empty (len(low) == 1 > len(high) == 0), sofindMedianreturns that value as a float. - Negative numbers: Negating negative integers works identically (
x = -4is stored inlowas4, and-self.low[0]recovers-4). Averaging-5and-4yields-4.5. - Duplicate values: Equal numbers can sit in both
lowandhigh(for instancelow = {5, 5},high = {5, 5}), which still satisfiesmax(low) <= min(high)and returns(5 + 5) / 2.0 = 5.0. - Strictly increasing or decreasing input: Every incoming number initially lands on the same side (
highwhen increasing,lowwhen decreasing), triggering one cross-heap transfer on every second insertion and keeping sizes within 1. - Empty stream: Calling
findMedianbefore anyaddNumsafely returnsNone.
Common mistakes
- Using floor division
// 2instead of/ 2.0:(6 + 9) // 2truncates7.5to7, and(-5 + -4) // 2floors-4.5down to-5. - Forgetting Python's
heapqis a min-heap: Pushing positivexdirectly intoself.lowplaces the minimum of the smaller half atself.low[0]instead of its maximum, breaking both placement and median reads. - Forgetting to flip the sign on BOTH push AND pop for
self.low: Moving a value betweenlowandhighrequires negating it in both directions (largest_in_low = -heapq.heappop(self.low)andheapq.heappush(self.low, -smallest_in_high)). - Balancing counts while ignoring value order: Alternating pushes into
lowandhighby count alone can leave a large value inlowand a small value inhigh(such aslow = {10},high = {2}). - 32-bit integer overflow in typed languages: In C++ or Java,
low.top() + high.top()can overflow a 32-bit signedintnear2 * 10^9; cast todouble(orlong long) before adding.
Alternative approaches
- Balanced binary search tree / order-statistic tree: In C++, a
std::multiset<int>paired with a persistent iterator to the middle element inserts in O(log n) and shifts the iterator by at most one step per insertion for O(1) median queries. It also supports arbitrary element deletion in O(log n), at the cost of per-node pointer allocations. - Sorted dynamic array (
bisect.insort): Compact code and O(1) median reads, but O(n) element shifting per insertion becomes too slow once n approaches10^5.
Follow-up questions
- How would you implement this two-heap tracker in C++, and what language-specific traps should you watch out for? In C++,
std::priority_queue<int>is already a max-heap by default, whilestd::priority_queue<int, std::vector<int>, std::greater<int>>is a min-heap, so no sign-negation trick is needed. Two traps to avoid: writelow.size() > high.size() + 1rather thanlow.size() - high.size() > 1(becausesize_tis unsigned and underflows whenhighis larger!), and cast todoublebefore adding the two tops soINT_MAX + INT_MAXcannot overflowint:
#include <functional>
#include <queue>
#include <vector>
class MedianFinder {
std::priority_queue<int> low; // max-heap: smaller half
std::priority_queue<int, std::vector<int>, std::greater<int>> high; // min-heap: larger half
public:
void addNum(int x) {
if (low.empty() || x <= low.top()) {
low.push(x);
} else {
high.push(x);
}
if (low.size() > high.size() + 1) {
high.push(low.top());
low.pop();
} else if (high.size() > low.size()) {
low.push(high.top());
high.pop();
}
}
double findMedian() const {
if (low.size() > high.size()) {
return static_cast<double>(low.top());
}
return (static_cast<double>(low.top()) + high.top()) / 2.0;
}
};
- If every incoming integer falls between 0 and 100 (or 99% of values do), how can you reduce time and space? Maintain a fixed frequency array
counts[0..100]alongsidetotal_count:addNum(x)incrementscounts[x]in O(1) time and O(1) space, andfindMedian()walks0..100summing frequencies until reaching the middle rank(s) in at most 101 steps. If 1% of values fall outside[0, 100], maintainbelow_zero_countandabove_hundred_count(or two small sorted containers for outliers): whenever fewer than 50% of values lie on each outlier side, the median rank is guaranteed to land inside[0, 100]and is found purely frombelow_zero_countpluscounts[0..100]. - How would you adapt the structure to compute the median over a sliding window of the most recent k numbers? Standard binary heaps cannot remove an arbitrary interior element in O(log k) time. Instead, use lazy deletion — recording expired outgoing values in a hash map
delayed[val] += 1, tracking each heap's count of live elements separately from its physical size, and popping expired values only once they surface atlow[0]orhigh[0]— achieving O(log k) amortized time per window step, or use two balanced multisets (SortedList/std::multiset) for direct O(log k) removal.
Follow-up questions
- How would you implement this two-heap tracker in C++, and what language-specific traps should you watch out for?
- If every incoming integer falls between 0 and 100 (or 99% of values do), how can you reduce time and space?
- How would you adapt the structure to compute the median over a sliding window of the most recent k numbers?
Similar questions
- Wildcard Word Lookup with a Prefix Tree
- Streaming Median Tracker
- Pointer Const-Qualification and C++ Associative Maps
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses