---
title: Running median
url: https://gurkanozkan.ai/learn/coding/mle-running-median-28/
markdown: https://gurkanozkan.ai/learn/coding/mle-running-median-28.md
kind: coding
difficulty: Medium
topics:
  - Heaps
  - Streaming
json: https://gurkanozkan.ai/api/learn/coding/mle-running-median-28.json
robots: noindex
---

# Running median

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

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

## Examples

Each call and the value it should give.

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

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

## Hints

1. Keep a max-heap (lo half) and a min-heap (hi half); balance |lo| - |hi| in {0, 1}.
2. Each step: O(log n) insert; median = middle for odd, mean of two middles for even.
3. Fix the heap invariant on equal values, not by re-sorting.

## Reference solution

```python
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.*
