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 k is odd, the median is the single center value v[k // 2].
  • When k is even, the median is the exact arithmetic average (v[k // 2 - 1] + v[k // 2]) / 2.0 of 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 integer x to the stream (including duplicates) and records None at that index in the output list.
  • "getMedian" paired with []: computes and records the current median as a float, or None if 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, and 10, the sorted values are [4, 8, 10], so the first "getMedian" returns the middle element 8.0.
    • Inserting 7 updates the sorted collection to [4, 7, 8, 10], so the second "getMedian" returns (7 + 8) / 2.0 = 7.5.

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 -6 produces sorted [-6, -6, -2], shifting the middle element back to -6.0.

Constraints

  • 0 <= len(operations) == len(arguments) <= 10^5
  • Every entry in operations is "add" or "getMedian".
  • For "add", arguments[i] contains a single integer x with -10^9 <= x <= 10^9.
  • For "getMedian", arguments[i] is [].

Step-by-step walkthrough

  1. 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 is 8.0.
    • Even count: there is no single middle slot, so the median is the average of the two middle values. Adding 7 gives 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 records None in the output list.
    • "getMedian" comes with [] and records the current median as a float (or None if no numbers have been added yet).
  2. 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 n numbers:

    1. Append on add, sort on getMedian: appending takes O(1) time, but sorting takes O(n log n) on every query. If getMedian is called after every add, n steps cost O(n^2 log n) time.
    2. Keep a sorted list with binary search (bisect.insort): binary search finds the insertion slot in O(log n) time, and getMedian just reads the middle index in O(1) time. However, inserting into the middle of a Python list forces every element to its right to shift one slot over in memory, which takes O(n) time per add and O(n^2) across n insertions.

    Notice why keeping the entire list sorted wastes work: getMedian never asks for the 5th number or the 90th percentile. It only ever looks at the 1 or 2 numbers right at the center border.

  3. 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 in O(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:

    1. Order invariant: every number in low is <= every number in high.
    2. Size invariant: len(low) == len(high) (when the total count is even) or len(low) == len(high) + 1 (when the total count is odd, so low holds 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 heapq module only provides a min-heap (smallest element at index 0). To turn self.low into 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], so self.low[0] is -2 and -self.low[0] gives 2 (the maximum).

  4. Insert a number and rebalance the two halves

    When add(x) arrives, we cannot blindly push x into whichever heap is smaller — if low holds {1} and high holds {5}, pushing 10 into low would put 10 in the "smaller half" and break the order invariant!

    Instead, add(x) works in two clean phases:

    1. Phase 1 — Route by value: compare x with -self.low[0] (the largest number in low). If low is empty or x <= -self.low[0], x belongs in the lower half (low). Otherwise x is strictly larger than everything in low, so it belongs in high.
    2. 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 (low now has 2 more items than high), pop the maximum of low and push it into high.
      • If len(high) > len(low) (high now has 1 more item than low), pop the minimum of high and push it (negated) into low.

    Moving a border element across never breaks the order invariant because low's maximum is guaranteed to be >= everything left in low and <= everything already in high (and symmetrically for high's minimum).

    Watch how a strictly descending stream 10, 9, 8 triggers 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)
    
  5. Read the median in O(1) time and wire up the stream

    Because len(self.low) >= len(self.high) is always true, checking if 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 and low holds the extra middle element, so -self.low[0] (converted to float) is the median.
    • When len(self.low) == len(self.high), the total count is even, so we average -self.low[0] and self.high[0] with / 2.0 (standard float division so odd sums like 2 + 3 keep their .5).

    Finally, median_stream steps through operations and arguments in lockstep. First, here is get_median on MedianFinder:

        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
    

    And here is the top-level median_stream driver 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
    
  6. Trace Example 1 step by step

    Let us trace operations = ["add", "add", "add", "getMedian", "add", "getMedian"] with arguments = [[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.5
    

    The returned list is [None, None, None, 8.0, None, 7.5], matching Example 1.

  7. 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]:

  1. add(8): low becomes {8}, high is {} (median is 8.0).
  2. add(4): 4 <= 8, so 4 enters low and rebalancing shifts 8 to high -> low = {4}, high = {8} (sizes 1 and 1, median is (4 + 8) / 2.0 = 6.0).
  3. add(10): 10 > 4, so 10 enters high and rebalancing shifts 8 back to low -> low = {4, 8}, high = {10} (sizes 2 and 1, odd count so median is max(low) = 8.0).
  4. add(7): 7 <= 8, so 7 enters low and rebalancing shifts 8 to high -> low = {4, 7}, high = {8, 10} (sizes 2 and 2, 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) per add(x) and O(1) per getMedian(), giving O(m log m) across m total calls. Each add performs 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 to log2(n). Each getMedian only peeks at index 0 of one or two heaps and performs at most one addition and division (O(1)).
  • Space: O(n) inside MedianFinder (plus O(m) for the returned results list), because every inserted integer is stored in exactly one of the two heaps with no extra copies.

Edge cases

  • Single element: low holds [ -x ] and high is empty, so len(low) == 1 > len(high) == 0 and getMedian() returns float(x).
  • Even count with an odd sum: [1, 2] returns (1 + 2) / 2.0 = 1.5; float division preserves the .5 fraction.
  • Duplicate values: copies of the same number can sit in both low and high (for example low = {4, 4}, high = {4, 4}), and both roots equal 4, so the median is still 4.0.
  • Negative integers: negating a negative number on push turns -7 into +7 inside self.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 to low; _rebalance shifts one border root across on every second add so the heap sizes never drift apart by more than 1.
  • Large integers near 10^9: Python integers have arbitrary precision, so largest_of_low + smallest_of_high never overflows before / 2.0. (In C++ or Java with 32-bit ints, widen to long or double before adding.)
  • getMedian before any add: self.low is empty, and our guard cleanly returns None.

Common mistakes

  • Forgetting one of the two minus signs on self.low: pushing x instead of -x, or reading self.low[0] instead of -self.low[0], turns low into 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} and high = {5}, pushing 10 directly into low just because sizes are equal puts 10 into the lower half (10 > 5), corrupting future medians. Always route by comparing with -self.low[0] first, then rebalance sizes.
  • Using integer division // 2 instead of / 2.0: (2 + 3) // 2 truncates 2.5 down to 2.
  • Mixing up which heap holds the extra item: if _rebalance lets low hold the extra item (len(low) == len(high) + 1), get_median must read -self.low[0] in the odd case, never self.high[0].

Alternative approaches

  • Sorted list with bisect.insort: binary search finds the insertion position in O(log n) and getMedian reads the middle index in O(1), but shifting array elements makes each add O(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 in O(log n) time. It supports add, arbitrary deletions, and any percentile in O(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 with lo and hi pointers, quickselect reorders the input array in place using O(1) extra memory and O(n) expected time (use 3-way Dutch National Flag partitioning so all-duplicate inputs stay O(n)). For an odd n, a[k] after selection is the median; for an even n, every element placed in a[0 : k] is guaranteed to be <= a[k], so one linear scan for max(a[0 : k]) finds the lower middle value to average with a[k] in O(1) extra memory. If O(n log n) worst-case time with O(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 <= mid on each pass in O(n log R) time and O(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 counts of size 101 along with a running integer total_count. Each add(x) increments counts[x] and total_count in O(1) time, and getMedian() walks counts[0..100] accumulating counts until it crosses the middle rank(s) in at most 101 steps (O(1) time and O(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 of low or high. Track separate low_size and high_size counters counting only live elements so rebalancing still maintains the exact middle split, then prune any marked roots from low[0] and high[0] before reading the median in O(log W) amortized time per step.

Follow-up questions

Similar questions

More Cognitiv interview questions

All 3 Cognitiv questions →