Running Median of an Integer Stream

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement a streaming median tracker exposed through the driver function:

def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:

Numbers arrive sequentially, interleaved with median lookups. Each index i pairs an operation name operations[i] with its argument list arguments[i]:

  • "addNum" with [x]: record integer x in the multiset of observed values and append None to the output list.
  • "findMedian" with []: compute the median of every integer recorded up to this point and append it as a float (if no integers have been recorded yet, append None).

How the median is defined when all k recorded integers are arranged in non-decreasing order:

  • Odd k: the single element at index k // 2.
  • Even k (k > 0): the exact floating-point mean (a + b) / 2.0 of the two central elements a and b.

Your data structure should process each "addNum" call in O(log n) time and answer each "findMedian" call in O(1) (or O(log n)) time, where n is the number of values inserted so far.

Examples

Example 1

Input:
  operations = ["addNum", "addNum", "findMedian", "addNum", "findMedian"]
  arguments  = [[6], [10], [], [2], []]

Output:
  [None, None, 8.0, None, 6.0]

Walk-through: After inserting 6 and 10, the sorted values are [6, 10], so "findMedian" returns (6 + 10) / 2.0 = 8.0. Inserting 2 updates the sorted values to [2, 6, 10], whose middle value is 6.0.

Example 2

Input:
  operations = ["addNum", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
  arguments  = [[-4], [-9], [-5], [], [2], []]

Output:
  [None, None, None, -5.0, None, -4.5]

Walk-through: After the first three insertions, the sorted stream is [-9, -5, -4], giving median -5.0. Appending 2 yields [-9, -5, -4, 2], and averaging the two central elements -5 and -4 gives (-5 + -4) / 2.0 = -4.5.

Constraints

  • 0 <= len(operations) == len(arguments) <= 10^5
  • Every operations[i] is either "addNum" (with arguments[i] = [x]) or "findMedian" (with arguments[i] = []).
  • Incoming values x are integers that may be negative, zero, or positive, and duplicate values are retained with full multiplicity.

Step-by-step walkthrough

  1. Understand the problem and median rules

    Integers arrive one at a time in a live stream, and at any point we can be asked for the median of everything observed so far:

    • Odd count: if we sorted all recorded numbers, the median is the single central value (for [2, 6, 10], the median is 6.0).
    • Even count: the median is the arithmetic mean of the two central values (for [6, 10], the median is (6 + 10) / 2.0 = 8.0).

    Values may be negative and may repeat ([5, 5, 1, 1] has sorted order [1, 1, 5, 5] and median (1 + 5) / 2.0 = 3.0).

    The driver function median_stream(operations, arguments) pairs "addNum" with [x] (appending None) and "findMedian" with [] (appending the float median, or None if no numbers have been inserted yet). With up to 10^5 operations, we want O(log n) per insertion and O(1) per query.

  2. Why sorting or keeping a sorted list is too slow

    Two straightforward list ideas both hit a bottleneck when 50,000 insertions are interleaved with 50,000 queries:

    • Append in O(1), sort on every findMedian: each sort costs O(n log n), adding up to billions of comparisons across 50,000 queries.
    • Maintain a sorted list with binary search (bisect.insort): reading the middle index is O(1), but inserting into the middle of a Python list shifts up to n elements in memory, making addNum O(n).

    Notice why both do wasted work: we never query arbitrary ranks like the 10th or 500th smallest element — we only ever inspect the boundary right at the center of the sorted order!

  3. Key idea: split the stream into two heaps

    Cut the sorted numbers cleanly in half at the median:

    • low holds the smaller half in a max-heap (a tree-based priority queue giving O(1) access to its largest value and O(log n) insertion/removal).
    • high holds the larger half in a min-heap (giving O(1) access to its smallest value and O(log n) insertion/removal).
    Sorted view:   [ 2,  4,  6  |  9, 10 ]
                     \_______/     \___/
                        low         high
                     (max-heap)  (min-heap)
                      top = 6     top = 9
    

    We maintain two invariants after every addNum:

    1. Order invariant: every number in low is <= every number in high (equivalently, max(low) <= min(high)).
    2. Size invariant: low has either the exact same size as high (even total count) or one more element than high (odd total count): len(low) == len(high) or len(low) == len(high) + 1.

    When both invariants hold, the center of the stream always sits right at low[0] and high[0]! Because Python's heapq module implements a min-heap, we simulate a max-heap in low by storing negated numbers (-x): the smallest negated entry self.low[0] corresponds to the largest original value -self.low[0].

  4. Insert a number and rebalance the two halves

    Each add_num(x) runs in two short phases:

    1. Pick the right heap (preserve Order): If low is empty or x <= -self.low[0], x belongs in the smaller half, so push -x into low. Otherwise x exceeds everything in low, so push x into high.
    2. Restore balance if needed (preserve Size): One insertion changes a heap's size by only 1, so at most one transfer across the center restores the size invariant:
      • If len(low) > len(high) + 1, pop low's largest value (-heapq.heappop(self.low)) and push it into high.
      • If len(high) > len(low), pop high's smallest value (heapq.heappop(self.high)) and push its negation into low.
    class MedianFinder:
        def __init__(self) -> None:
            # low: max-heap of the smaller half, stored negated because heapq is a min-heap.
            # Example: real values {1, 2} are stored as [-2, -1], so -self.low[0] == 2 (largest of low).
            self.low: List[int] = []
            # high: min-heap of the larger half, stored as-is.
            # Example: real values {3, 4} are stored as [3, 4], so self.high[0] == 3 (smallest of high).
            self.high: List[int] = []
    
        def add_num(self, x: int) -> None:
            # Phase 1: Place x into the half it belongs to so max(low) <= min(high) stays true.
            if not self.low or x <= -self.low[0]:
                heapq.heappush(self.low, -x)
            else:
                heapq.heappush(self.high, x)
    
            # Phase 2: Rebalance sizes so len(low) is always equal to len(high) or len(high) + 1.
            if len(self.low) > len(self.high) + 1:
                largest_in_low = -heapq.heappop(self.low)
                heapq.heappush(self.high, largest_in_low)
            elif len(self.high) > len(self.low):
                smallest_in_high = heapq.heappop(self.high)
                heapq.heappush(self.low, -smallest_in_high)
    
  5. Read the median in O(1) time

    Because our Size invariant guarantees len(low) is either len(high) + 1 or len(high), find_median never mutates either heap — it simply peeks at index 0:

    • When len(low) > len(high), the total count is odd, and low holds the extra middle value -self.low[0].
    • Otherwise len(low) == len(high), so the total count is even, and we average -self.low[0] and self.high[0] with true float division / 2.0 (never floor division // 2, which would round -4.5 down to -5).
        def find_median(self) -> Optional[float]:
            if not self.low:
                return None
    
            max_of_low = -self.low[0]
            # Odd total count: low holds the 1 extra middle element.
            if len(self.low) > len(self.high):
                return float(max_of_low)
    
            # Even total count: average the two middle elements with true float division '/'.
            min_of_high = self.high[0]
            return (max_of_low + min_of_high) / 2.0
    
  6. Dispatch operations and trace Example 2

    The driver median_stream creates one MedianFinder instance and steps through operations and arguments.

    def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
        finder = MedianFinder()
        results: List[Optional[float]] = []
    
        # Process each stream event in arrival order.
        for op, args in zip(operations, arguments):
            if op == "addNum":
                finder.add_num(args[0])
                results.append(None)
            elif op == "findMedian":
                results.append(finder.find_median())
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    Let's trace Example 2 (addNum(-4), addNum(-9), addNum(-5), findMedian(), addNum(2), findMedian()), showing the real values in each half alongside what self.low stores negated:

    1. addNum(-4):
       low is empty -> push to low
       low real: {-4} (stored as [4]),  high: {}             sizes 1, 0 (ok)
    
    2. addNum(-9):
       -9 <= max(low) (-4) -> push to low -> low real: {-9, -4}, sizes 2, 0 (low too big!)
       rebalance: pop max(low) = -4, push to high
       low real: {-9} (stored as [9]),  high: [-4]           sizes 1, 1 (ok)
    
    3. addNum(-5):
       -5 > max(low) (-9) -> push to high -> high: [-5, -4], sizes 1, 2 (high too big!)
       rebalance: pop min(high) = -5, push to low
       low real: {-9, -5} (stored as [5, 9]),  high: [-4]    sizes 2, 1 (ok)
    
    4. findMedian():
       len(low) > len(high) -> max(low) = -self.low[0] = -5.0
    
    5. addNum(2):
       2 > max(low) (-5) -> push to high
       low real: {-9, -5} (stored as [5, 9]),  high: [-4, 2] sizes 2, 2 (ok)
    
    6. findMedian():
       len(low) == len(high) -> (-5 + -4) / 2.0 = -4.5
    

    The returned list is [None, None, None, -5.0, None, -4.5].

  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, stored negated because heapq is a min-heap.
            # Example: real values {1, 2} are stored as [-2, -1], so -self.low[0] == 2 (largest of low).
            self.low: List[int] = []
            # high: min-heap of the larger half, stored as-is.
            # Example: real values {3, 4} are stored as [3, 4], so self.high[0] == 3 (smallest of high).
            self.high: List[int] = []
    
        def add_num(self, x: int) -> None:
            # Phase 1: Place x into the half it belongs to so max(low) <= min(high) stays true.
            if not self.low or x <= -self.low[0]:
                heapq.heappush(self.low, -x)
            else:
                heapq.heappush(self.high, x)
    
            # Phase 2: Rebalance sizes so len(low) is always equal to len(high) or len(high) + 1.
            if len(self.low) > len(self.high) + 1:
                largest_in_low = -heapq.heappop(self.low)
                heapq.heappush(self.high, largest_in_low)
            elif len(self.high) > len(self.low):
                smallest_in_high = heapq.heappop(self.high)
                heapq.heappush(self.low, -smallest_in_high)
    
        def find_median(self) -> Optional[float]:
            if not self.low:
                return None
    
            max_of_low = -self.low[0]
            # Odd total count: low holds the 1 extra middle element.
            if len(self.low) > len(self.high):
                return float(max_of_low)
    
            # Even total count: average the two middle elements with true float division '/'.
            min_of_high = self.high[0]
            return (max_of_low + min_of_high) / 2.0
    
    
    def median_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
        finder = MedianFinder()
        results: List[Optional[float]] = []
    
        # Process each stream event in arrival order.
        for op, args in zip(operations, arguments):
            if op == "addNum":
                finder.add_num(args[0])
                results.append(None)
            elif op == "findMedian":
                results.append(finder.find_median())
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a growing crowd split into two balanced teams on either side of a center line: everyone on the left team is shorter than (or equal to) everyone on the right team. Neither team needs to stand in full sorted order — as long as the tallest person on the left team and the shortest person on the right team stand right at the center line, you can read the median height instantly! We model those two teams with two heaps — tree-based priority queues that expose their extreme element at index 0 in O(1) time while supporting pushes and pops in O(log n) time: a max-heap low (keeping the largest value of the smaller half on top) and a min-heap high (keeping the smallest value of the larger half on top).

Naive list-based designs waste effort ordering elements far away from the middle. Appending to an unsorted list and sorting on every findMedian costs O(n log n) per query, while inserting into a sorted list (bisect.insort) shifts up to n items in memory, costing O(n) per addNum. Across 50,000 insertions and 50,000 lookups, both list approaches degrade to quadratic total work, whereas two heaps finish each addNum in O(log n) time and each findMedian in O(1) time.

Walk through Example 1 where 6, 10, and 2 arrive:

  1. addNum(6): low is empty, so 6 goes into low. Now low = {6}, high = {}, and the median would be 6.0.
  2. addNum(10): 10 > max(low) (6), so 10 goes into high. Now low = {6} (size 1) and high = {10} (size 1) are already balanced, so findMedian() averages the two tops: (6 + 10) / 2.0 = 8.0.
  3. addNum(2): 2 <= max(low) (6), so 2 goes into low, making low = {2, 6} (size 2, top 6) and high = {10} (size 1, top 10). Since len(low) == len(high) + 1, no rebalance is needed, and findMedian() returns max(low) = 6.0. (Whenever an insertion pushes a heap two ahead on the left or one ahead on the right, a single pop-and-push across the boundary restores balance.)

Complexity

Let n be the number of integers inserted so far and m be the total number of operations.

  • addNum time — O(log n): We compare x against low's top in O(1), run one heap push in O(log n), and if the heap sizes violate the balance rule, run one heap pop and one heap push in O(log n). At most three heap operations execute per insertion.
  • findMedian time — O(1): We read self.low[0] (plus self.high[0] when the count is even) without mutating either heap. Over m total operations, the full run takes O(m log m) time.
  • Space — O(n): Each inserted integer resides in either self.low or self.high once, storing n integers in total.

Edge cases

  • Single element: low holds that element and high is empty (len(low) == 1 > len(high) == 0), so findMedian returns that value as a float.
  • Negative numbers: Negating negative integers works identically (x = -4 is stored in low as 4, and -self.low[0] recovers -4). Averaging -5 and -4 yields -4.5.
  • Duplicate values: Equal numbers can sit in both low and high (for instance low = {5, 5}, high = {5, 5}), which still satisfies max(low) <= min(high) and returns (5 + 5) / 2.0 = 5.0.
  • Strictly increasing or decreasing input: Every incoming number initially lands on the same side (high when increasing, low when decreasing), triggering one cross-heap transfer on every second insertion and keeping sizes within 1.
  • Empty stream: Calling findMedian before any addNum safely returns None.

Common mistakes

  • Using floor division // 2 instead of / 2.0: (6 + 9) // 2 truncates 7.5 to 7, and (-5 + -4) // 2 floors -4.5 down to -5.
  • Forgetting Python's heapq is a min-heap: Pushing positive x directly into self.low places the minimum of the smaller half at self.low[0] instead of its maximum, breaking both placement and median reads.
  • Forgetting to flip the sign on BOTH push AND pop for self.low: Moving a value between low and high requires negating it in both directions (largest_in_low = -heapq.heappop(self.low) and heapq.heappush(self.low, -smallest_in_high)).
  • Balancing counts while ignoring value order: Alternating pushes into low and high by count alone can leave a large value in low and a small value in high (such as low = {10}, high = {2}).
  • 32-bit integer overflow in typed languages: In C++ or Java, low.top() + high.top() can overflow a 32-bit signed int near 2 * 10^9; cast to double (or long long) before adding.

Alternative approaches

  • Balanced binary search tree / order-statistic tree: In C++, a std::multiset<int> paired with a persistent iterator to the middle element inserts in O(log n) and shifts the iterator by at most one step per insertion for O(1) median queries. It also supports arbitrary element deletion in O(log n), at the cost of per-node pointer allocations.
  • Sorted dynamic array (bisect.insort): Compact code and O(1) median reads, but O(n) element shifting per insertion becomes too slow once n approaches 10^5.

Follow-up questions

  • How would you implement this two-heap tracker in C++, and what language-specific traps should you watch out for? In C++, std::priority_queue<int> is already a max-heap by default, while std::priority_queue<int, std::vector<int>, std::greater<int>> is a min-heap, so no sign-negation trick is needed. Two traps to avoid: write low.size() > high.size() + 1 rather than low.size() - high.size() > 1 (because size_t is unsigned and underflows when high is larger!), and cast to double before adding the two tops so INT_MAX + INT_MAX cannot overflow int:
#include <functional>
#include <queue>
#include <vector>

class MedianFinder {
    std::priority_queue<int> low;                                        // max-heap: smaller half
    std::priority_queue<int, std::vector<int>, std::greater<int>> high;  // min-heap: larger half

public:
    void addNum(int x) {
        if (low.empty() || x <= low.top()) {
            low.push(x);
        } else {
            high.push(x);
        }
        if (low.size() > high.size() + 1) {
            high.push(low.top());
            low.pop();
        } else if (high.size() > low.size()) {
            low.push(high.top());
            high.pop();
        }
    }

    double findMedian() const {
        if (low.size() > high.size()) {
            return static_cast<double>(low.top());
        }
        return (static_cast<double>(low.top()) + high.top()) / 2.0;
    }
};
  • If every incoming integer falls between 0 and 100 (or 99% of values do), how can you reduce time and space? Maintain a fixed frequency array counts[0..100] alongside total_count: addNum(x) increments counts[x] in O(1) time and O(1) space, and findMedian() walks 0..100 summing frequencies until reaching the middle rank(s) in at most 101 steps. If 1% of values fall outside [0, 100], maintain below_zero_count and above_hundred_count (or two small sorted containers for outliers): whenever fewer than 50% of values lie on each outlier side, the median rank is guaranteed to land inside [0, 100] and is found purely from below_zero_count plus counts[0..100].
  • How would you adapt the structure to compute the median over a sliding window of the most recent k numbers? Standard binary heaps cannot remove an arbitrary interior element in O(log k) time. Instead, use lazy deletion — recording expired outgoing values in a hash map delayed[val] += 1, tracking each heap's count of live elements separately from its physical size, and popping expired values only once they surface at low[0] or high[0] — achieving O(log k) amortized time per window step, or use two balanced multisets (SortedList / std::multiset) for direct O(log k) removal.

Follow-up questions

Similar questions

More Trexquant interview questions

All 4 Trexquant questions →