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,000 calls to add_num and at most 50,000 calls to find_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

  1. Restate the problem and how the judge calls our code

    Integers arrive dynamically one at a time. We need a MedianFinder class supporting: - add_num(num): record a newly arrived integer. - find_median(): return the current median as a float — 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) from starter.py, replaying operation names ("MedianFinder", "add_num", "find_median") alongside their argument lists ([] or [num]) and collecting None for setup/insertions and float answers for queries.

    With up to 50,000 insertions and 50,000 queries: - Re-sorting an array on every find_median takes O(n log n) per query — billions of operations overall. - Maintaining a sorted list with bisect.insort shifts up to n items in O(n) per insertion — O(n^2) worst-case total.

    We want O(log n) per insertion and O(1) per median query.

  2. 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 0 and updates in O(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.5
    

    We maintain two invariants (properties guaranteed at the end of every add_num): 1. Partition order: Every value in lower_half is <= every value in upper_half. 2. Size balance: Either len(lower_half) == len(upper_half) (even count) or len(lower_half) == len(upper_half) + 1 (odd count, giving the extra central item to lower_half).

    Because Python's heapq only implements a min-heap (smallest value at heap[0]), we turn lower_half into 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 -4 at index 0, so -self.lower_half[0] immediately gives 4.

  3. Step-by-step insertion: place, then rebalance

    Each add_num(num) call restores both invariants in two clean phases:

    1. Place (Partition order): If lower_half is empty or num <= -self.lower_half[0], num belongs in the lower half, so push -num onto lower_half. Otherwise num exceeds everything in lower_half, so push num onto upper_half.
    2. Rebalance (Size balance): One insertion changes the size gap by at most 1:
      • If len(lower_half) > len(upper_half) + 1 (lower_half is two ahead), pop its maximum (negating back to positive) and push it into upper_half.
      • If len(upper_half) > len(lower_half) (upper_half pulled ahead), pop its minimum and push its negation into lower_half.
    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)
    
  4. Read the median in O(1) and write the judge wrapper

    With both invariants satisfied, find_median() only inspects index 0 in O(1) time: - When len(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.0 using 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.0
    

    Finally, median_finder(operations, arguments) iterates through zip(operations, arguments) to instantiate MedianFinder(), call add_num, or append find_median().

  5. 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.5
    
  6. Complete 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 one heappush, plus at most one heappop and one heappush to restore size balance; each heap holds at most (n + 1) // 2 elements, so every heap operation traverses at most log2(n) tree levels.
  • find_median: O(1) time. We inspect self.lower_half[0] (and self.upper_half[0] when n is 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 (plus O(m) for the returned transcript list).

Edge cases

  • Single value inserted ([-3]): add_num pushes it onto lower_half (len == 1, upper_half empty), and find_median returns float(-self.lower_half[0]) without reading upper_half.
  • Repeated identical numbers ([9, 9, 9, 9]): Every 9 satisfies num <= -self.lower_half[0], enters lower_half, and shifts over to upper_half whenever lower_half pulls two ahead; both roots stay 9, yielding 9.0.
  • Negative values and half-integers ([-1, -2]): Sign flips keep -(-1) == 1 and -(-2) == 2 consistent, while true float division (-2 + -1) / 2.0 produces -1.5.
  • Back-to-back find_median calls: Because find_median peeks at index 0 without popping, consecutive queries leave heap state unchanged.

Common mistakes

  • Forgetting sign negation when transferring items between heaps: lower_half stores -x whereas upper_half stores +x. Pushing heapq.heappop(self.lower_half) directly into upper_half without negating corrupts upper_half with negative values.
  • Using floor division // 2 instead of / 2.0: (4 + 7) // 2 truncates 5.5 to 5, and (-2 + -1) // 2 floors -1.5 to -2.
  • Alternating heaps blindly by turn: Sending odd-numbered arrivals to lower_half and even-numbered arrivals to upper_half without checking num <= -self.lower_half[0] violates partition order (for 4, 10, 12, lower_half would hold {4, 12} and upper_half {10}, returning 12.0 instead of 10.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 inside upper_half.

Alternative approaches

  • Unconditional two-way push-pop: Always push -num into lower_half, immediately pop lower_half's max into upper_half, and if len(upper_half) > len(lower_half), pop upper_half's min back into lower_half. It is very compact and still O(log n), though every insertion executes 2–3 heap 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 in O(log R) time over range size R = 200,001) can maintain exact counts and locate the middle order statistics in O(log R) time and O(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,001 integer counters indexed by num + 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 error epsilon in 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 last W values 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 in O(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 counts of length 101 alongside a running total count n: add_num(num) increments counts[num] in O(1) time, and find_median() scans the 101 buckets accumulating counts until reaching rank n // 2 in O(101) = O(1) constant time and O(1) constant space.

Follow-up questions

Similar questions

More Xiaopeng interview questions

All 1 Xiaopeng questions →