Skip to content
mlmentorship

Find Median From Data Stream

Maintain ordered lower and upper heaps at completed insertions, distinguish repair states, and adapt float medians to exact fractions or nearest-rank quantiles.

Published · 25 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Find Median From Data Stream

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

After completed insertions, ordered halves and balanced sizes expose the middle ranks at the heap roots.

Problem trace

Read the median only after both heap ordering and size repair are complete

Input and goalAdd numbers one at a time and return the current median.
Initialize two empty heapsBoth heaps start empty, so a median query is undefined. Negated lower values make its stored minimum the logical maximum.
heapstored valueslogical role
lower[]max-heap via negatives
upper[]min-heap
stream[5,2,10,4]statusinitialized: no median yet
stream
[5,2,10,4]
status
initialized: no median yet
heap / row 0
lower

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.
Both heaps start empty, so a median query is undefined. Negated lower values make its stored minimum the logical maximum. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the median query unsafe midway through inserting 10 even when heap sizes temporarily fit?
Full interview answer 25 min read

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 valueLogical lower heapUpper heapMedian
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

Read the median only after both heap ordering and size repair are completeMaintain ordered lower and upper halves, with lower equal in size or one larger. Completed roots give the odd middle or even midpoint. Pushing ten breaks order; the next transfer breaks size balance. Finish both repairs before reading. Heaps are not sorted arrays. Keep all inserted values; repeats count and deletion is absent. Float medians can round or overflow; exact fractions or another quantile change the output contract.Completed roots expose the middleranksInsert five, two, ten, four. Theseare logical heap members and extrema,not a claim that each heap array issorted.Added 5; completed median 5Lower maximum5Members: 5Size 1Upper minimumnoneMembers: emptySize 0Added 2; completed median 3.5Lower maximum2Members: 2Size 1Upper minimum5Members: 5Size 1Added 10; completed median 5Lower maximum5Members: 5, 2Size 2Upper minimum10Members: 10Size 1Added 4; completed median 4.5Lower maximum4Members: 4, 2Size 2Upper minimum5Members: 5, 10Size 2Inside the insertion of ten: do notquery repair framesPush ten: order fails, size allowedLower maximum10Members: 10, 2Size 2Upper minimum5Members: 5Size 1Transfer maximum: order holds, sizefailsLower maximum2Members: 2Size 1Upper minimum5Members: 5, 10Size 2Transfer minimum back: both holdLower maximum5Members: 5, 2Size 2Upper minimum10Members: 10Size 1Transfer lower maximum to upper;then, if upper is larger, return itsminimum to lower. Both completedinvariants must hold before readingroots.Python stores negatives in the lowermin-heap to represent a logicalmax-heap. Odd counts use its root;even counts average the two logicalroots.All history remains: logarithmic heapupdates, constant root queries,linear value storage. Repeats count;no deletion. Empty source queryraises IndexError.Float conversion can round oroverflow huge integers. Exactfractions preserve roots;nearest-rank quantiles instead changethe lower target size and need notaverage even samples.
Read it this way: Maintain ordered lower and upper halves, with lower equal in size or one larger. Completed roots give the odd middle or even midpoint. Pushing ten breaks order; the next transfer breaks size balance. Finish both repairs before reading. Heaps are not sorted arrays. Keep all inserted values; repeats count and deletion is absent. Float medians can round or overflow; exact fractions or another quantile change the output contract. After pushing ten, do acceptable heap sizes alone permit a median query?
Reference drawing

Problem trace

Read the median only after both heap ordering and size repair are complete

Read the median only after both heap ordering and size repair are completeMaintain ordered lower and upper halves, with lower equal in size or one larger. Completed roots give the odd middle or even midpoint. Pushing ten breaks order; the next transfer breaks size balance. Finish both repairs before reading. Heaps are not sorted arrays. Keep all inserted values; repeats count and deletion is absent. Float medians can round or overflow; exact fractions or another quantile change the output contract.Completed roots expose the middleranksInsert five, two, ten, four. Theseare logical heap members and extrema,not a claim that each heap array issorted.Added 5; completed median 5Lower maximum5Members: 5Size 1Upper minimumnoneMembers: emptySize 0Added 2; completed median 3.5Lower maximum2Members: 2Size 1Upper minimum5Members: 5Size 1Added 10; completed median 5Lower maximum5Members: 5, 2Size 2Upper minimum10Members: 10Size 1Added 4; completed median 4.5Lower maximum4Members: 4, 2Size 2Upper minimum5Members: 5, 10Size 2Inside the insertion of ten: do notquery repair framesPush ten: order fails, size allowedLower maximum10Members: 10, 2Size 2Upper minimum5Members: 5Size 1Transfer maximum: order holds, sizefailsLower maximum2Members: 2Size 1Upper minimum5Members: 5, 10Size 2Transfer minimum back: both holdLower maximum5Members: 5, 2Size 2Upper minimum10Members: 10Size 1Transfer lower maximum to upper;then, if upper is larger, return itsminimum to lower. Both completedinvariants must hold before readingroots.Python stores negatives in the lowermin-heap to represent a logicalmax-heap. Odd counts use its root;even counts average the two logicalroots.All history remains: logarithmic heapupdates, constant root queries,linear value storage. Repeats count;no deletion. Empty source queryraises IndexError.Float conversion can round oroverflow huge integers. Exactfractions preserve roots;nearest-rank quantiles instead changethe lower target size and need notaverage even samples.
Execution trace
Input and goalAdd numbers one at a time and return the current median.
Initialize two empty heapsBoth heaps start empty, so a median query is undefined. Negated lower values make its stored minimum the logical maximum.
heapstored valueslogical role
lower[]max-heap via negatives
upper[]min-heap
stream[5,2,10,4]statusinitialized: no median yet
stream
[5,2,10,4]
status
initialized: no median yet
heap / row 0
lower

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.
Both heaps start empty, so a median query is undefined. Negated lower values make its stored minimum the logical maximum. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the median query unsafe midway through inserting 10 even when heap sizes temporarily fit?
Read it this way: Maintain ordered lower and upper halves, with lower equal in size or one larger. Completed roots give the odd middle or even midpoint. Pushing ten breaks order; the next transfer breaks size balance. Finish both repairs before reading. Heaps are not sorted arrays. Keep all inserted values; repeats count and deletion is absent. Float medians can round or overflow; exact fractions or another quantile change the output contract. After pushing ten, do acceptable heap sizes alone permit a median query?

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.

  1. Keep exact integer medians.

    New task: Avoid rounding or overflow from float conversion.

    Picture and change: Reuse source insertion unchanged. Build a Fraction from 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 answer

    Check: [5,2,10,4] gives ["5","7/2","5","9/2"]. The singleton integer 10000000000000001 remains 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.

  2. 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 answer

    Check: [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.