Streaming Integer Median Tracker
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an online tracker MedianFinder that ingests integers arriving sequentially and reports the statistical median of all values observed up to the current moment.
When k values have been recorded and sorted in non-decreasing order:
- If k is odd, the median equals the central value at index k // 2 (returned as a float).
- If k is even, the median equals the exact floating-point mean of the two central values at indices k // 2 - 1 and k // 2.
Support the class interface below along with the test-harness driver median_finder(operations, arguments), where each entry i executes operations[i] with arguments[i]:
- "MedianFinder" (arguments[i] == []): instantiate a fresh MedianFinder and record None.
- "add_num" (arguments[i] == [num]): insert num into the active tracker and record None.
- "find_median" (arguments[i] == []): query the current median (only invoked when at least one integer has been added) and record the resulting float.
class MedianFinder:
def __init__(self) -> None: ...
def add_num(self, num: int) -> None: ...
def find_median(self) -> float: ...
def median_finder(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
Examples
Example 1
Input:
operations = ["MedianFinder", "add_num", "add_num", "find_median", "add_num", "find_median", "add_num", "find_median"]
arguments = [[], [10], [4], [], [7], [], [2], []]
Output:
[None, None, None, 7.0, None, 7.0, None, 5.5]
After inserting 10 and 4, the sorted values are [4, 10], whose mean is (4 + 10) / 2 = 7.0. Inserting 7 gives [4, 7, 10], with central element 7.0. Inserting 2 gives [2, 4, 7, 10], whose two middle values 4 and 7 average to 5.5.
Example 2
Input:
operations = ["MedianFinder", "add_num", "find_median", "add_num", "add_num", "find_median"]
arguments = [[], [-3], [], [-3], [-6], []]
Output:
[None, None, -3.0, None, None, -3.0]
With a single value [-3], the median is -3.0. After appending -3 and -6, the sorted multiset is [-6, -3, -3], whose middle element is still -3.0.
Constraints
1 <= len(operations) == len(arguments) <= 100,001- At most
50,000calls toadd_numand at most50,000calls tofind_median. -10^5 <= num <= 10^5- Every
"find_median"call occurs after at least one"add_num"call on the active instance.
Step-by-step walkthrough
Restate the problem and how the judge calls our code
Integers arrive dynamically one at a time. We need a
MedianFinderclass supporting: -add_num(num): record a newly arrived integer. -find_median(): return the current median as afloat— the single central element when the total count is odd, or the floating-point mean of the two central elements when the total count is even.The judge invokes
median_finder(operations, arguments)fromstarter.py, replaying operation names ("MedianFinder","add_num","find_median") alongside their argument lists ([]or[num]) and collectingNonefor setup/insertions andfloatanswers for queries.With up to
50,000insertions and50,000queries: - Re-sorting an array on everyfind_mediantakesO(n log n)per query — billions of operations overall. - Maintaining a sorted list withbisect.insortshifts up tonitems inO(n)per insertion —O(n^2)worst-case total.We want
O(log n)per insertion andO(1)per median query.Key idea: split the numbers into two heaps around the center
Finding the median never requires full order inside the lower half or full order inside the upper half — we only need the largest number in the lower half and the smallest number in the upper half.
A heap (a tree-structured priority queue backed by a Python list) keeps its extreme item at index
0and updates inO(log n)time. We place two heaps back-to-back around the median cut:Sorted view: [ 2, 4 | 7, 10 ] \___/ \____/ lower_half upper_half (max-heap) (min-heap) top = 4 top = 7 --> median = (4 + 7) / 2.0 = 5.5We maintain two invariants (properties guaranteed at the end of every
add_num): 1. Partition order: Every value inlower_halfis<=every value inupper_half. 2. Size balance: Eitherlen(lower_half) == len(upper_half)(even count) orlen(lower_half) == len(upper_half) + 1(odd count, giving the extra central item tolower_half).Because Python's
heapqonly implements a min-heap (smallest value atheap[0]), we turnlower_halfinto a max-heap by negating numbers on insertion (-num) and negating again when reading or popping (-self.lower_half[0]). Storing{2, 4}as[-4, -2]keeps-4at index0, so-self.lower_half[0]immediately gives4.Step-by-step insertion: place, then rebalance
Each
add_num(num)call restores both invariants in two clean phases:- Place (
Partition order): Iflower_halfis empty ornum <= -self.lower_half[0],numbelongs in the lower half, so push-numontolower_half. Otherwisenumexceeds everything inlower_half, so pushnumontoupper_half. - Rebalance (
Size balance): One insertion changes the size gap by at most1:- If
len(lower_half) > len(upper_half) + 1(lower_halfis two ahead), pop its maximum (negating back to positive) and push it intoupper_half. - If
len(upper_half) > len(lower_half)(upper_halfpulled ahead), pop its minimum and push its negation intolower_half.
- If
class MedianFinder: def __init__(self): self.lower_half: List[int] = [] self.upper_half: List[int] = [] def add_num(self, num: int) -> None: # Phase 1: Place num while keeping every element in lower_half <= every element in upper_half. if not self.lower_half or num <= -self.lower_half[0]: heapq.heappush(self.lower_half, -num) else: heapq.heappush(self.upper_half, num) # Phase 2: Rebalance sizes so len(lower_half) == len(upper_half) or len(upper_half) + 1. if len(self.lower_half) > len(self.upper_half) + 1: moved_val = -heapq.heappop(self.lower_half) heapq.heappush(self.upper_half, moved_val) elif len(self.upper_half) > len(self.lower_half): moved_val = heapq.heappop(self.upper_half) heapq.heappush(self.lower_half, -moved_val)- Place (
Read the median in O(1) and write the judge wrapper
With both invariants satisfied,
find_median()only inspects index0inO(1)time: - Whenlen(lower_half) > len(upper_half), the count is odd and-self.lower_half[0]is the exact middle value. - Otherwise both heaps have identical lengths, so we return(-self.lower_half[0] + self.upper_half[0]) / 2.0using true float division.def find_median(self) -> float: largest_in_lower = -self.lower_half[0] if len(self.lower_half) > len(self.upper_half): return float(largest_in_lower) smallest_in_upper = self.upper_half[0] return (largest_in_lower + smallest_in_upper) / 2.0Finally,
median_finder(operations, arguments)iterates throughzip(operations, arguments)to instantiateMedianFinder(), calladd_num, or appendfind_median().Trace Example 1 step by step
Let's trace
10,4,find_median,7,find_median,2,find_median— notice how this sequence exercises both rebalance directions:1. add_num(10): Place: lower_half is empty -> push -10 into lower_half. Logical halves: lower={10} (top 10), upper={} 2. add_num(4): Place: 4 <= 10 -> push -4 into lower_half -> lower has {4, 10}, upper has {}. Rebalance (lower -> upper): len(lower)=2 > len(upper)+1 -> move 10 to upper_half. Logical halves: lower={4} (top 4), upper={10} (top 10) 3. find_median(): Sizes equal (1 == 1) -> (4 + 10) / 2.0 = 7.0 4. add_num(7): Place: 7 > 4 -> push 7 into upper_half -> lower has {4}, upper has {7, 10}. Rebalance (upper -> lower): len(upper)=2 > len(lower)=1 -> move 7 to lower_half. Logical halves: lower={4, 7} (top 7), upper={10} (top 10) 5. find_median(): len(lower)=2 > len(upper)=1 -> float(7) = 7.0 6. add_num(2): Place: 2 <= 7 -> push -2 into lower_half -> lower has {2, 4, 7}, upper has {10}. Rebalance (lower -> upper): len(lower)=3 > len(upper)+1 -> move 7 to upper_half. Logical halves: lower={2, 4} (top 4), upper={7, 10} (top 7) 7. find_median(): Sizes equal (2 == 2) -> (4 + 7) / 2.0 = 5.5Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq class MedianFinder: def __init__(self): # lower_half: max-heap of the smaller half, stored as negated ints because heapq is a min-heap # (e.g., [-4, -2] represents {2, 4}, so -lower_half[0] == 4 is the largest small number). self.lower_half: List[int] = [] # upper_half: min-heap of the larger half, stored as plain ints # (e.g., [7, 10] represents {7, 10}, so upper_half[0] == 7 is the smallest large number). self.upper_half: List[int] = [] def add_num(self, num: int) -> None: # Phase 1: Place num while keeping every element in lower_half <= every element in upper_half. # Using <= puts values tied with the current middle into lower_half. if not self.lower_half or num <= -self.lower_half[0]: heapq.heappush(self.lower_half, -num) else: heapq.heappush(self.upper_half, num) # Phase 2: Rebalance sizes so len(lower_half) == len(upper_half) (even count) # or len(lower_half) == len(upper_half) + 1 (odd count). if len(self.lower_half) > len(self.upper_half) + 1: # Negate back to positive when moving lower_half's largest value into upper_half. moved_val = -heapq.heappop(self.lower_half) heapq.heappush(self.upper_half, moved_val) elif len(self.upper_half) > len(self.lower_half): # Negate when moving upper_half's smallest value into lower_half. moved_val = heapq.heappop(self.upper_half) heapq.heappush(self.lower_half, -moved_val) def find_median(self) -> float: # With an odd total count, lower_half holds the extra middle element at its root. largest_in_lower = -self.lower_half[0] if len(self.lower_half) > len(self.upper_half): return float(largest_in_lower) # With an even total count, average the two middle values using true float division. smallest_in_upper = self.upper_half[0] return (largest_in_lower + smallest_in_upper) / 2.0 def median_finder(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]: # Replay the judge's method-call transcript and collect one return value per operation. finder = MedianFinder() results: List[Optional[float]] = [] for op, args in zip(operations, arguments): if op == "MedianFinder": finder = MedianFinder() results.append(None) elif op == "add_num": finder.add_num(args[0]) results.append(None) elif op == "find_median": results.append(finder.find_median()) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine lining people up by height solely to know who stands in the exact middle. You do not actually need to sort everyone end-to-end — you only need two rooms: a "shorter half" room where the tallest occupant stands right by the door, and a "taller half" room where the shortest occupant stands right by the door! Whenever both rooms hold equal counts (or the shorter room holds just 1 extra person), the median is always standing right at those two doorways.
Why do plain array approaches fall short? Appending to an unsorted list and calling sorted() on each find_median costs O(n log n) per query, whereas keeping a sorted list via bisect.insort shifts up to n elements in O(n) per insertion — both stall across 50,000 updates and 50,000 queries. Instead, we model the two rooms with heaps (tree-based priority queues stored in lists that keep the extreme item at index 0 and insert or pop in O(log n) time): a max-heap (largest item on top, simulated in Python's heapq min-heap by negating values -num) for lower_half, and a min-heap (smallest item on top) for upper_half.
Here is a 4-number walkthrough inserting [10, 4, 7, 2] and reading the median at each step:
add 10 -> lower={10}, upper={} | odd -> top of lower = 10.0
add 4 -> lower={4, 10} -> rebalance moves 10 -> lower={4}, upper={10}
| even -> (4 + 10) / 2.0 = 7.0
add 7 -> 7 > 4 -> upper={7, 10} -> rebalance moves 7 -> lower={4, 7}, upper={10}
| odd -> top of lower = 7.0
add 2 -> 2 <= 7 -> lower={2, 4, 7} -> rebalance moves 7 -> lower={2, 4}, upper={7, 10}
| even -> (4 + 7) / 2.0 = 5.5
Complexity
Let n be the number of integers inserted so far, and m be len(operations).
add_num:O(log n)time. Each insertion performs oneheappush, plus at most oneheappopand oneheappushto restore size balance; each heap holds at most(n + 1) // 2elements, so every heap operation traverses at mostlog2(n)tree levels.find_median:O(1)time. We inspectself.lower_half[0](andself.upper_half[0]whennis even) and perform constant-time float arithmetic without mutating either heap.- Total driver time:
O(m log n), and Space:O(n)across the two heap arrays (plusO(m)for the returned transcript list).
Edge cases
- Single value inserted (
[-3]):add_numpushes it ontolower_half(len == 1,upper_halfempty), andfind_medianreturnsfloat(-self.lower_half[0])without readingupper_half. - Repeated identical numbers (
[9, 9, 9, 9]): Every9satisfiesnum <= -self.lower_half[0], enterslower_half, and shifts over toupper_halfwheneverlower_halfpulls two ahead; both roots stay9, yielding9.0. - Negative values and half-integers (
[-1, -2]): Sign flips keep-(-1) == 1and-(-2) == 2consistent, while true float division(-2 + -1) / 2.0produces-1.5. - Back-to-back
find_mediancalls: Becausefind_medianpeeks at index0without popping, consecutive queries leave heap state unchanged.
Common mistakes
- Forgetting sign negation when transferring items between heaps:
lower_halfstores-xwhereasupper_halfstores+x. Pushingheapq.heappop(self.lower_half)directly intoupper_halfwithout negating corruptsupper_halfwith negative values. - Using floor division
// 2instead of/ 2.0:(4 + 7) // 2truncates5.5to5, and(-2 + -1) // 2floors-1.5to-2. - Alternating heaps blindly by turn: Sending odd-numbered arrivals to
lower_halfand even-numbered arrivals toupper_halfwithout checkingnum <= -self.lower_half[0]violates partition order (for4, 10, 12,lower_halfwould hold{4, 12}andupper_half{10}, returning12.0instead of10.0). - Only rebalancing in one direction: Omitting the
elif len(self.upper_half) > len(self.lower_half)branch causes strictly rising inputs to pile up insideupper_half.
Alternative approaches
- Unconditional two-way push-pop: Always push
-numintolower_half, immediately poplower_half's max intoupper_half, and iflen(upper_half) > len(lower_half), popupper_half's min back intolower_half. It is very compact and stillO(log n), though every insertion executes2–3heap operations unconditionally. - Fenwick tree over value frequencies: Because inputs lie within
[-10^5, 10^5], a Fenwick tree (also called a Binary Indexed Tree — an array structure supporting bucket updates and prefix-sum queries inO(log R)time over range sizeR = 200,001) can maintain exact counts and locate the middle order statistics inO(log R)time andO(R)fixed memory.
Follow-up questions
- What changes if billions of values arrive over time and RAM cannot hold every element? When values stay bounded in
[-10^5, 10^5], replace the two heaps with a fixed frequency array (200,001integer counters indexed bynum + 100000, taking only a few megabytes regardless of stream length) paired with a Fenwick tree for middle-rank queries. For arbitrary 64-bit integers, no single-pass algorithm can compute the exact median in sublinear RAM, so production pipelines use a quantile sketch (a compact summary such as KLL or t-digest that merges nearby values into weighted buckets to guarantee a tiny rank errorepsilonin kilobytes of memory). - How would you maintain the median over only the most recent W arrivals (a fixed-size sliding window)? Standard heaps cannot remove an arbitrary expired element from the interior in
O(log W)time, so pair a FIFO queue of the lastWvalues with lazy deletion on the two heaps: track logical active sizes per heap, record evicted values in a hash map of pending-delete counts, and physically pop stale entries whenever they reach a heap root. Alternatively, use a balanced order-statistic tree (or a Fenwick tree if values are bounded) to insert new arrivals, delete expired ones, and query the middle rank directly inO(log W)time. - How fast can insertions and queries run if every incoming integer lies inside a tiny fixed interval such as 0 to 100? Maintain an integer array
countsof length101alongside a running total countn:add_num(num)incrementscounts[num]inO(1)time, andfind_median()scans the101buckets accumulating counts until reaching rankn // 2inO(101) = O(1)constant time andO(1)constant space.
Follow-up questions
- What changes if billions of values arrive over time and RAM cannot hold every element?
- How would you maintain the median over only the most recent W arrivals (a fixed-size sliding window)?
- How fast can insertions and queries run if every incoming integer lies inside a tiny fixed interval such as 0 to 100?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array