Design a data structure for efficiently retrieving the median from a stream of integers.

Instruction: Design an insert-only integer stream structure with efficient median retrieval. Explain heap ordering/balance invariants, empty input, exact even-count results, time/space complexity and what changes for a sliding window.

Context: This question challenges candidates to combine their knowledge of data structures and algorithms to solve a complex problem involving dynamic sets of data.

Updated

Official answer

For an insert-only integer stream, keep the lower half in a max-heap and the upper half in a min-heap. The lower heap has either the same number of entries or one extra, and every lower value is at most every upper value.

import heapq
from fractions import Fraction

class StreamingMedian:
    def __init__(self):
        self.lower = []  # negated values implement a max-heap
        self.upper = []

    def add(self, value):
        if not isinstance(value, int):
            raise TypeError('integer required')
        heapq.heappush(self.lower, -value)
        heapq.heappush(self.upper, -heapq.heappop(self.lower))
        if len(self.upper) > len(self.lower):
            heapq.heappush(self.lower, -heapq.heappop(self.upper))

    def median(self):
        if not self.lower:
            raise ValueError('empty stream')
        if len(self.lower) > len(self.upper):
            return -self.lower[0]
        return Fraction(-self.lower[0] + self.upper[0], 2)

Fraction preserves an exact half-integer result without float rounding, including for very large Python integers. Under a fixed-cost arithmetic/comparison model, insertion is O(log n), retrieval O(1), and storage O(n); arbitrary-size integer operations add bit-level costs.

This retains all observations. A sliding-window median needs deletion support, often with indexed heaps or carefully managed lazy deletion and rebalancing. Bounded-memory approximate quantiles are a different contract. Test duplicates, negatives, ascending/descending arrivals, an empty stream and both even and odd counts.

Related Questions