LearnCoding

Running median

MediumHeaps, Streaming

Problem

After each new element, output the median of all elements seen so far as a float. For an even count, use the mean of the two middle values. Each step must take O(log n).

Signature

def running_median(stream: list[float]) -> list[float]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(running_median([5, 15, 1, 3]), [5.0, 10.0, 5.0, 4.0])
True

>>> close(running_median([1]), [1.0])
True

Solve it in your own editor; nothing on this page runs code.

Hints

Keep a max-heap (lo half) and a min-heap (hi half); balance |lo| - |hi| in {0, 1}.

Each step: O(log n) insert; median = middle for odd, mean of two middles for even.

Fix the heap invariant on equal values, not by re-sorting.

Reference solution

import heapq

def running_median(stream):
    lo, hi, out = [], [], []
    for x in stream:
        if not lo or x <= -lo[0]:
            heapq.heappush(lo, -x)
        else:
            heapq.heappush(hi, x)
        if len(lo) > len(hi) + 1:
            heapq.heappush(hi, -heapq.heappop(lo))
        elif len(hi) > len(lo):
            heapq.heappush(lo, -heapq.heappop(hi))
        out.append(float(-lo[0]) if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2)
    return out

What a strong solution covers

  • Two heaps (a max-heap via negation, and a min-heap), with the balance invariant |lo| − |hi| ∈ {0, 1}.
  • O(log n) per step.
  • Discusses sliding-window medians (lazy deletion) and approximate quantile sketches (t-digest, KLL) for monitoring.

Common mistakes

  • re-sorting every step (O(n log n) per element)
  • breaking the heap invariant on equal values.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.