Running Median of an Integer Stream
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Build an online tracker that ingests integers from a sequential stream and reports the median of all numbers observed up to any point in time.
Recall how the median of k sorted values v[0] <= v[1] <= ... <= v[k - 1] is defined:
- When
kis odd, the median is the single center valuev[k // 2]. - When
kis even, the median is the exact arithmetic average(v[k // 2 - 1] + v[k // 2]) / 2.0of the two center values.
Implement the driver function:
def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
You are given two parallel lists operations and arguments of equal length, replaying calls against a single fresh tracker instance:
"add"paired with[x]: appends integerxto the stream (including duplicates) and recordsNoneat that index in the output list."getMedian"paired with[]: computes and records the current median as afloat, orNoneif zero numbers have been added so far.
Return the list of recorded outputs across all operations.
Examples
Example 1
- Input:
operations = ["add", "add", "add", "getMedian", "add", "getMedian"]arguments = [[8], [4], [10], [], [7], []]
- Output:
[None, None, None, 8.0, None, 7.5] - Explanation:
- After inserting
8,4, and10, the sorted values are[4, 8, 10], so the first"getMedian"returns the middle element8.0. - Inserting
7updates the sorted collection to[4, 7, 8, 10], so the second"getMedian"returns(7 + 8) / 2.0 = 7.5.
- After inserting
Example 2
- Input:
operations = ["add", "getMedian", "add", "getMedian", "add", "getMedian"]arguments = [[-6], [], [-2], [], [-6], []]
- Output:
[None, -6.0, None, -4.0, None, -6.0] - Explanation:
- With
[-6], the median is-6.0. - After adding
-2, the sorted pair[-6, -2]has median(-6 + -2) / 2.0 = -4.0. - Adding a second
-6produces sorted[-6, -6, -2], shifting the middle element back to-6.0.
- With
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every entry in
operationsis"add"or"getMedian". - For
"add",arguments[i]contains a single integerxwith-10^9 <= x <= 10^9. - For
"getMedian",arguments[i]is[].
Step-by-step walkthrough
Understand the goal and the stream interface
Integers arrive one at a time in a live stream, and at any moment we can be asked for the median of all numbers inserted so far:
- Odd count: if we sorted the numbers, the median is the exact middle value. For
[8, 4, 10], sorted order is[4, 8, 10], so the median is8.0. - Even count: there is no single middle slot, so the median is the average of the two middle values. Adding
7gives sorted[4, 7, 8, 10], and the median is(7 + 8) / 2.0 = 7.5.
The automated judge calls
median_stream(operations, arguments):"add"comes with[x](one integer to insert) and recordsNonein the output list."getMedian"comes with[]and records the current median as afloat(orNoneif no numbers have been added yet).
- Odd count: if we sorted the numbers, the median is the exact middle value. For
Why keeping a sorted list is too slow
Before designing a specialized data structure, let us check why simple list approaches bottleneck on a long stream of
nnumbers:- Append on
add, sort ongetMedian: appending takesO(1)time, but sorting takesO(n log n)on every query. IfgetMedianis called after everyadd,nsteps costO(n^2 log n)time. - Keep a sorted list with binary search (
bisect.insort): binary search finds the insertion slot inO(log n)time, andgetMedianjust reads the middle index inO(1)time. However, inserting into the middle of a Pythonlistforces every element to its right to shift one slot over in memory, which takesO(n)time peraddandO(n^2)acrossninsertions.
Notice why keeping the entire list sorted wastes work:
getMediannever asks for the 5th number or the 90th percentile. It only ever looks at the 1 or 2 numbers right at the center border.- Append on
Key idea: split the stream into two heaps at the middle
A heap is a tree-based priority queue stored inside a flat array that lets us peek at its extreme value in
O(1)time and insert or remove that extreme value inO(log n)time, without fully sorting the remaining elements.If we split all seen numbers into a lower half and an upper half, we only care about the largest number in the lower half and the smallest number in the upper half:
smaller half (low) middle larger half (high) ------------------ border ------------------ [ ... , 1 , 2 ] <-- max = 2 | min = 3 --> [ 3 , 4 , ... ] (max-heap) | (min-heap)We maintain two simple rules (invariants) after every
add:- Order invariant: every number in
lowis<=every number inhigh. - Size invariant:
len(low) == len(high)(when the total count is even) orlen(low) == len(high) + 1(when the total count is odd, solowholds the one extra middle element).
When both invariants hold, the median is always sitting right at the heap tops!
One small Python detail: Python's built-in
heapqmodule only provides a min-heap (smallest element at index0). To turnself.lowinto a max-heap, we negate every number when pushing it in and negate it again when reading or popping it out. For example,{1, 2}is stored as[-2, -1], soself.low[0]is-2and-self.low[0]gives2(the maximum).- Order invariant: every number in
Insert a number and rebalance the two halves
When
add(x)arrives, we cannot blindly pushxinto whichever heap is smaller — iflowholds{1}andhighholds{5}, pushing10intolowwould put10in the "smaller half" and break the order invariant!Instead,
add(x)works in two clean phases:- Phase 1 — Route by value: compare
xwith-self.low[0](the largest number inlow). Iflowis empty orx <= -self.low[0],xbelongs in the lower half (low). Otherwisexis strictly larger than everything inlow, so it belongs inhigh. - Phase 2 — Rebalance sizes: Phase 1 grew one heap by
1, which can stretch the size gap by at most one step:- If
len(low) > len(high) + 1(lownow has 2 more items thanhigh), pop the maximum oflowand push it intohigh. - If
len(high) > len(low)(highnow has 1 more item thanlow), pop the minimum ofhighand push it (negated) intolow.
- If
Moving a border element across never breaks the order invariant because
low's maximum is guaranteed to be>=everything left inlowand<=everything already inhigh(and symmetrically forhigh's minimum).Watch how a strictly descending stream
10, 9, 8triggers rebalancing automatically:add(10): low empty -> push 10 to low | low={10}, high={} (sizes 1, 0: ok) add(9): 9 <= 10 -> push 9 to low | low={9, 10}, high={} (sizes 2, 0: low too big!) rebalance -> move max(low)=10 | low={9}, high={10} (sizes 1, 1: ok) add(8): 8 <= 9 -> push 8 to low | low={8, 9}, high={10} (sizes 2, 1: ok, median = 9)Here is the class setup,
add, and_rebalance:from typing import Any, Dict, List, Optional, Set, Tuple import heapq class MedianFinder: def __init__(self) -> None: # low: max-heap of the smaller half of numbers seen so far. # Python's heapq is a min-heap, so we negate values on push and pop: # e.g., real numbers {1, 2} are stored as [-2, -1] so -self.low[0] == 2. self.low: List[int] = [] # high: min-heap of the larger half of numbers seen so far, # e.g., [3, 4] so self.high[0] == 3. self.high: List[int] = [] def add(self, x: int) -> None: # Phase 1: Route x to the half where it belongs so every value in low # stays <= every value in high. Compare against low's maximum (-self.low[0]). if not self.low or x <= -self.low[0]: heapq.heappush(self.low, -x) else: heapq.heappush(self.high, x) # Phase 2: Restore the size invariant: len(low) == len(high) (even total) # or len(low) == len(high) + 1 (odd total, low holds the 1 extra middle value). self._rebalance() def _rebalance(self) -> None: if len(self.low) > len(self.high) + 1: # low has 2 more items than high: move low's maximum across to high. largest_of_low = -heapq.heappop(self.low) heapq.heappush(self.high, largest_of_low) elif len(self.high) > len(self.low): # high has 1 more item than low: move high's minimum across to low. smallest_of_high = heapq.heappop(self.high) heapq.heappush(self.low, -smallest_of_high)- Phase 1 — Route by value: compare
Read the median in O(1) time and wire up the stream
Because
len(self.low) >= len(self.high)is always true, checkingif not self.low:tells us immediately whether zero items have been inserted. Otherwise:- When
len(self.low) > len(self.high), the total count is odd andlowholds the extra middle element, so-self.low[0](converted tofloat) is the median. - When
len(self.low) == len(self.high), the total count is even, so we average-self.low[0]andself.high[0]with/ 2.0(standard float division so odd sums like2 + 3keep their.5).
Finally,
median_streamsteps throughoperationsandargumentsin lockstep. First, here isget_medianonMedianFinder:def get_median(self) -> Optional[float]: # Because len(low) >= len(high) always holds, an empty low means 0 items added. if not self.low: return None largest_of_low = -self.low[0] if len(self.low) > len(self.high): # Odd total count: low holds the extra item, so its maximum is the median. return float(largest_of_low) # Even total count: average the two middle border values using float division. smallest_of_high = self.high[0] return (largest_of_low + smallest_of_high) / 2.0And here is the top-level
median_streamdriver that the judge calls:def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]: # Replay each operation in order against one MedianFinder and collect outputs. finder = MedianFinder() results: List[Optional[float]] = [] for op, args in zip(operations, arguments): if op == "add": finder.add(args[0]) results.append(None) else: results.append(finder.get_median()) return results- When
Trace Example 1 step by step
Let us trace
operations = ["add", "add", "add", "getMedian", "add", "getMedian"]witharguments = [[8], [4], [10], [], [7], []]:Step Call Action self.low self.high Output ---- ----------- ------------------------------------------------- ----------- ---------- ------ 1 add(8) low empty -> push -8 to low [-8] [] None 2 add(4) 4 <= 8 -> push -4 to low; rebalance moves 8->high [-4] [8] None 3 add(10) 10 > 4 -> push 10 to high; rebalance moves 8->low [-8, -4] [10] None 4 getMedian() len(low)=2 > len(high)=1 -> -(-8) [-8, -4] [10] 8.0 5 add(7) 7 <= 8 -> push -7 to low; rebalance moves 8->high [-7, -4] [8, 10] None 6 getMedian() sizes 2 == 2 -> (7 + 8) / 2.0 [-7, -4] [8, 10] 7.5The returned list is
[None, None, None, 8.0, None, 7.5], matching Example 1.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 of numbers seen so far. # Python's heapq is a min-heap, so we negate values on push and pop: # e.g., real numbers {1, 2} are stored as [-2, -1] so -self.low[0] == 2. self.low: List[int] = [] # high: min-heap of the larger half of numbers seen so far, # e.g., [3, 4] so self.high[0] == 3. self.high: List[int] = [] def add(self, x: int) -> None: # Phase 1: Route x to the half where it belongs so every value in low # stays <= every value in high. Compare against low's maximum (-self.low[0]). if not self.low or x <= -self.low[0]: heapq.heappush(self.low, -x) else: heapq.heappush(self.high, x) # Phase 2: Restore the size invariant: len(low) == len(high) (even total) # or len(low) == len(high) + 1 (odd total, low holds the 1 extra middle value). self._rebalance() def _rebalance(self) -> None: if len(self.low) > len(self.high) + 1: # low has 2 more items than high: move low's maximum across to high. largest_of_low = -heapq.heappop(self.low) heapq.heappush(self.high, largest_of_low) elif len(self.high) > len(self.low): # high has 1 more item than low: move high's minimum across to low. smallest_of_high = heapq.heappop(self.high) heapq.heappush(self.low, -smallest_of_high) def get_median(self) -> Optional[float]: # Because len(low) >= len(high) always holds, an empty low means 0 items added. if not self.low: return None largest_of_low = -self.low[0] if len(self.low) > len(self.high): # Odd total count: low holds the extra item, so its maximum is the median. return float(largest_of_low) # Even total count: average the two middle border values using float division. smallest_of_high = self.high[0] return (largest_of_low + smallest_of_high) / 2.0 def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]: # Replay each operation in order against one MedianFinder and collect outputs. finder = MedianFinder() results: List[Optional[float]] = [] for op, args in zip(operations, arguments): if op == "add": finder.add(args[0]) results.append(None) else: results.append(finder.get_median()) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining students up by height in a gym to report the median height as new students walk through the door one by one. You do not actually need every student in exact sorted order — you only need to split the room into two equal-sized groups ("shorter half" and "taller half") and keep track of the tallest student in the shorter group and the shortest student in the taller group, because those two stand right at the center line.
The obvious approach of appending each number to a list and sorting on every getMedian() call costs O(n log n) per query, and even keeping a list sorted with binary search (bisect.insort) costs O(n) per add(x) because inserting into the middle of an array shifts every later element one slot to the right. Across n arrivals, both approaches degrade to O(n^2) or O(n^2 log n) total work.
Instead, we maintain two heaps — a heap is a tree-based priority queue stored in a list that lets us read its extreme item in O(1) time and insert or pop that item in O(log n) time. Specifically, low is a max-heap (a heap whose root is its largest value, simulated in Python's heapq by negating numbers) holding the smaller half, and high is a min-heap (a heap whose root is its smallest value) holding the larger half, with low allowed at most one extra item. Walk through [8, 4, 10, 7]:
add(8):lowbecomes{8},highis{}(median is8.0).add(4):4 <= 8, so4enterslowand rebalancing shifts8tohigh->low = {4},high = {8}(sizes1and1, median is(4 + 8) / 2.0 = 6.0).add(10):10 > 4, so10entershighand rebalancing shifts8back tolow->low = {4, 8},high = {10}(sizes2and1, odd count so median ismax(low) = 8.0).add(7):7 <= 8, so7enterslowand rebalancing shifts8tohigh->low = {4, 7},high = {8, 10}(sizes2and2, even count so median is(max(low) + min(high)) / 2.0 = (7 + 8) / 2.0 = 7.5).
Complexity
Let n be the number of integers inserted so far and m be the total number of operations.
- Time:
O(log n)peradd(x)andO(1)pergetMedian(), givingO(m log m)acrossmtotal calls. Eachaddperforms one heap push (O(log n)), plus at most one heap pop and one heap push during_rebalance(O(log n)), because each heap has height proportional tolog2(n). EachgetMedianonly peeks at index0of one or two heaps and performs at most one addition and division (O(1)). - Space:
O(n)insideMedianFinder(plusO(m)for the returnedresultslist), because every inserted integer is stored in exactly one of the two heaps with no extra copies.
Edge cases
- Single element:
lowholds[ -x ]andhighis empty, solen(low) == 1 > len(high) == 0andgetMedian()returnsfloat(x). - Even count with an odd sum:
[1, 2]returns(1 + 2) / 2.0 = 1.5; float division preserves the.5fraction. - Duplicate values: copies of the same number can sit in both
lowandhigh(for examplelow = {4, 4},high = {4, 4}), and both roots equal4, so the median is still4.0. - Negative integers: negating a negative number on push turns
-7into+7insideself.low, and negating again on read restores-7, preserving the exact order-7 < -3 < -1. - Sorted or reverse-sorted streams: ascending inputs after the first all route to
high, and descending inputs all route tolow;_rebalanceshifts one border root across on every secondaddso the heap sizes never drift apart by more than1. - Large integers near
10^9: Python integers have arbitrary precision, solargest_of_low + smallest_of_highnever overflows before/ 2.0. (In C++ or Java with 32-bitints, widen tolongordoublebefore adding.) getMedianbefore anyadd:self.lowis empty, and our guard cleanly returnsNone.
Common mistakes
- Forgetting one of the two minus signs on
self.low: pushingxinstead of-x, or readingself.low[0]instead of-self.low[0], turnslowinto a min-heap and reads the smallest element of the lower half instead of the largest. - Pushing into the smaller heap without checking value order first: if
low = {1}andhigh = {5}, pushing10directly intolowjust because sizes are equal puts10into the lower half (10 > 5), corrupting future medians. Always route by comparing with-self.low[0]first, then rebalance sizes. - Using integer division
// 2instead of/ 2.0:(2 + 3) // 2truncates2.5down to2. - Mixing up which heap holds the extra item: if
_rebalanceletslowhold the extra item (len(low) == len(high) + 1),get_medianmust read-self.low[0]in the odd case, neverself.high[0].
Alternative approaches
- Sorted list with
bisect.insort: binary search finds the insertion position inO(log n)andgetMedianreads the middle index inO(1), but shifting array elements makes eachaddO(n)in the worst case. - Order-statistic tree: an order-statistic tree is a self-balancing binary search tree where every node also stores the count of nodes in its subtree so you can look up any
k-th smallest item inO(log n)time. It supportsadd, arbitrary deletions, and any percentile inO(log n)time, though Python's standard library does not include one and two heaps are much simpler when only the median is needed.
Follow-up questions
- Suppose the entire array of integers is already in memory and you need O(1) auxiliary space — how would you find its median? Use quickselect — an in-place selection algorithm that partitions the array around a random pivot (just like quicksort) and loops into only the one side containing index
k = n // 2. Written iteratively withloandhipointers, quickselect reorders the input array in place usingO(1)extra memory andO(n)expected time (use 3-way Dutch National Flag partitioning so all-duplicate inputs stayO(n)). For an oddn,a[k]after selection is the median; for an evenn, every element placed ina[0 : k]is guaranteed to be<= a[k], so one linear scan formax(a[0 : k])finds the lower middle value to average witha[k]inO(1)extra memory. IfO(n log n)worst-case time withO(1)extra space is preferred, use in-place heapsort; if the input array cannot be modified at all, binary search on the value range[min(a), max(a)]and count how many elements are<= midon each pass inO(n log R)time andO(1)extra space. - How could you achieve O(1) updates and queries if every incoming integer is guaranteed to fall between 0 and 100? Replace the two heaps with a fixed-length frequency array
countsof size101along with a running integertotal_count. Eachadd(x)incrementscounts[x]andtotal_countinO(1)time, andgetMedian()walkscounts[0..100]accumulating counts until it crosses the middle rank(s) in at most101steps (O(1)time andO(1)space that never grows with stream length). - How would you adapt the two-heap design to support a sliding window where older elements expire as new ones arrive? Standard heaps cannot delete an arbitrary interior value in
O(log W)time, so pair the two heaps with lazy deletion — a technique where outgoing numbers are recorded in a hash map of pending removals (delayed[x] += 1) and only physically popped when they eventually bubble up to the top ofloworhigh. Track separatelow_sizeandhigh_sizecounters counting only live elements so rebalancing still maintains the exact middle split, then prune any marked roots fromlow[0]andhigh[0]before reading the median inO(log W)amortized time per step.
Follow-up questions
- Suppose the entire array of integers is already in memory and you need O(1) auxiliary space — how would you find its median?
- How could you achieve O(1) updates and queries if every incoming integer is guaranteed to fall between 0 and 100?
- How would you adapt the two-heap design to support a sliding window where older elements expire as new ones arrive?
Similar questions
- Real-Time ML Feature Platform for Ranking
- High-Throughput Spark Streaming Deduplication at Scale
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance