Accept integers one at a time and report the median of all values inserted so far.
Problem
Input. Calls to add_num(num) and find_median() on an initially empty MedianFinder.
Output. Each median query returns the middle sorted value, or the average of both middle values for an even count.
Rules. Inserted values are integers; repeats count separately.
The reference returns floating-point answers and retains the full history, not a sliding window.
There is no deletion operation. Query only after insertion; an empty query raises IndexError.
Extremely large integers may overflow the reference’s float conversion.
Example. Insert 1, then 2: find_median() returns 1.5.
After inserting 3, it returns 2.0, regardless of the insertion order of those three values.
Picture
At every completed insertion, maintain both conditions:
- Every logical lower-half value is at most every upper-half value.
- Lower has the same size as upper, or exactly one extra value.
Thus lower’s maximum is the odd middle rank. For even size, lower’s maximum and upper’s minimum bound the midpoint. Neither condition alone is sufficient.
| Added value | Logical lower heap | Upper heap | Median |
|---|---|---|---|
5 | [5] | [] | 5.0 |
2 | [2] | [5] | 3.5 |
10 | [5,2] | [10] | 5.0 |
4 | [4,2] | [5,10] | 4.5 |
Each heap orders parent against children, not the whole array.
This Python 3.12 implementation stores negatives in lower; its minimum stored root represents the logical maximum.
First push into lower. Transfer its maximum to upper, repairing cross-partition order. If upper is larger, transfer its minimum back, repairing the required sizes without breaking order.
Repair frames may violate either final condition. After pushing ten, lower’s logical root ten exceeds upper’s root five, despite acceptable sizes. After pushing two, lower has two values and upper none, despite ordered partitions. Read a median only after the complete insertion.
Source output is float. Huge integer medians may round or overflow during conversion; heap storage alone does not guarantee exact output.
Problem trace
Read the median only after both heap ordering and size repair are complete
Reference drawing
Problem trace
Read the median only after both heap ordering and size repair are complete
Execution trace
| heap | stored values | logical role |
|---|---|---|
| lower | [] | max-heap via negatives |
| upper | [] | min-heap |
- stream
- [5,2,10,4]
- status
- initialized: no median yet
- heap / row 0
- lower
lower max-heap
- 5
upper min-heap
empty- seen
- not shown→5
- status
- initialized: no median yet→insertion repair: not a query point
- partition order
- not shown→all lower <= all upper
lower max-heap
emptyupper min-heap
- 5
- sizes
- lower 1, upper 0: final size rule holds→lower 0, upper 1: final size rule violated
- root summary
- lower 5, upper none→lower none, upper 5
- lower stored
- [-5]→[]
lower max-heap
- 5
upper min-heap
empty- status
- insertion repair: not a query point→completed insertion: query allowed
- sizes
- lower 0, upper 1: final size rule violated→lower 1, upper 0: final size rule holds
- root summary
- lower none, upper 5→lower 5, upper none
lower max-heap
- 5
upper min-heap
empty- branch
- not shown→lower larger
- result
- not shown→5.0
- balance
- 1 >= 0 and difference=1→not shown
lower max-heap
- 5
- 2
upper min-heap
empty- seen
- 5→5, 2
- status
- completed insertion: query allowed→insertion repair: not a query point
- sizes
- lower 1, upper 0: final size rule holds→lower 2, upper 0: final size rule violated
lower max-heap
- 2
upper min-heap
- 5
- status
- insertion repair: not a query point→completed insertion: query allowed
- sizes
- lower 2, upper 0: final size rule violated→lower 1, upper 1: final size rule holds
- root summary
- lower 5, upper none→lower 2, upper 5
lower max-heap
- 2
upper min-heap
- 5
- arithmetic
- not shown→(2+5)/2
- result
- not shown→3.5
- rebalance
- 1 > 1 is false→not shown
lower max-heap
- 10
- 2
upper min-heap
- 5
- seen
- 5, 2→5, 2, 10
- status
- completed insertion: query allowed→insertion repair: not a query point
- partition order
- all lower <= all upper→violated: lower root 10 > upper root 5
lower max-heap
- 2
upper min-heap
- 5
- 10
- partition order
- violated: lower root 10 > upper root 5→all lower <= all upper
- sizes
- lower 2, upper 1: final size rule holds→lower 1, upper 2: final size rule violated
- root summary
- lower 10, upper 5→lower 2, upper 5
lower max-heap
- 5
- 2
upper min-heap
- 10
- status
- insertion repair: not a query point→completed insertion: query allowed
- sizes
- lower 1, upper 2: final size rule violated→lower 2, upper 1: final size rule holds
- root summary
- lower 2, upper 5→lower 5, upper 10
lower max-heap
- 5
- 2
upper min-heap
- 10
- branch
- not shown→lower larger
- result
- not shown→5.0
- balance
- sizes 2 and 1→not shown
lower max-heap
- 5
- 2
- 4
upper min-heap
- 10
- seen
- 5, 2, 10→5, 2, 10, 4
- status
- completed insertion: query allowed→insertion repair: not a query point
- sizes
- lower 2, upper 1: final size rule holds→lower 3, upper 1: final size rule violated
lower max-heap
- 4
- 2
upper min-heap
- 5
- 10
- status
- insertion repair: not a query point→completed insertion: query allowed
- sizes
- lower 3, upper 1: final size rule violated→lower 2, upper 2: final size rule holds
- root summary
- lower 5, upper 10→lower 4, upper 5
lower max-heap
- 4
- 2
upper min-heap
- 5
- 10
- arithmetic
- not shown→(4+5)/2
- result
- not shown→4.5
- rebalance
- 2 > 2 is false→not shown
- Recognize it
- Use two heaps when numbers arrive online and every median query must avoid sorting the entire history.
- Keep true
- After each completed insertion, every lower value is at most every upper value, and lower has either equal size or one extra item. These two conditions expose the middle ranks at roots. Repair frames need not satisfy them.
- Reuse it
- Maintain an ordered partition whose size difference is bounded, then answer rank queries from boundary roots. The same balancing idea supports streaming quantiles and running order statistics.
Code
import heapq
class MedianFinder:
def __init__(self) -> None:
self.lower: list[int] = []
self.upper: list[int] = []
def add_num(self, num: int) -> None:
heapq.heappush(self.lower, -num)
heapq.heappush(self.upper, -heapq.heappop(self.lower))
if len(self.upper) > len(self.lower):
heapq.heappush(self.lower, -heapq.heappop(self.upper))
def find_median(self) -> float:
if len(self.lower) > len(self.upper):
return float(-self.lower[0])
return (-self.lower[0] + self.upper[0]) / 2
Cost: After insertions, updates take heap work, queries root operations, and retained storage values. These bounds exclude integer-width and conversion costs.
Change Numeric Output or the Rank
Start from MedianFinder. Change either numeric representation or which rank the partition exposes.
-
Keep exact integer medians.
New task: Avoid rounding or overflow from float conversion.
Picture and change: Reuse source insertion unchanged. Build a
Fractionfrom one root or the integer sum of two roots. The helper returns strings only to display a prefix trace.Code: Complete helper using the source class above:
from fractions import Fraction def exact_median_trace(values): finder, answer = MedianFinder(), [] for value in values: finder.add_num(value) if len(finder.lower) > len(finder.upper): median = Fraction(-finder.lower[0], 1) else: median = Fraction(-finder.lower[0] + finder.upper[0], 2) answer.append(str(median)) return answerCheck:
[5,2,10,4]gives["5","7/2","5","9/2"]. The singleton integer10000000000000001remains exact, unlike its rounded float conversion.Use when: Integer-rank arithmetic must be exact. Fraction construction, formatting and returned strings add bit-width work and output storage.
-
Choose one nearest-rank quantile.
New task: Return rank , without midpoint averaging.
Picture and change: Define using positive integers with
numerator <= denominator. Keep that target number of items in lower. Place each new value by partition order, then transfer boundary roots to repair size.Code: Complete replacement:
import heapq def quantile_trace(values, numerator, denominator): if not 0 < numerator <= denominator: raise ValueError("invalid quantile") lower, upper, answer = [], [], [] for count, value in enumerate(values, 1): if not lower or value <= -lower[0]: heapq.heappush(lower, -value) else: heapq.heappush(upper, value) needed = (numerator * count + denominator - 1) // denominator while len(lower) > needed: heapq.heappush(upper, -heapq.heappop(lower)) while len(lower) < needed: heapq.heappush(lower, -heapq.heappop(upper)) answer.append(-lower[0]) return answerCheck:
[5,2,10,4]gives[5,2,2,2]for , or[5,5,10,5]for . At , even samples return the lower middle value, not the averaged median.Use when: One fixed rank definition replaces the median. Updates remain logarithmic and retain all values; returned answers add storage. This is not a bounded-memory quantile sketch.
Rebuild the Retention Decision
Why not discard values outside a bounded top- heap?
Answer: Future insertions can move the middle rank. Exact median maintenance retains both ordered halves, unlike bounded top- retention.