Median of a data stream
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The median is the middle value when numbers are sorted. For a stream where numbers keep arriving, you can keep it up to date by splitting the numbers into a smaller half and a larger half, so the middle is always at the top of one of the halves.
Practical use cases
- Web app: Median delivery time on a live dashboard. An operations dashboard shows "Median delivery time: 28 minutes", updated after every order. Re-sorting thousands of times is wasteful. Two heaps hold the faster and slower halves, so each new delivery is placed in a few steps and the middle is always ready. The number never needs a recount.
- Web app: Typical response time in a monitoring page. A developer page shows the median API response time, which is less thrown off by a few very slow requests than the average. As each request finishes, the number is added to the halves. The graph stays live with millions of requests a day.
- System: Finance, sensors and matchmaking. Trading tools track the median price of a stream, sensor systems track a typical reading while ignoring spikes, and matchmaking services keep the median skill of waiting players to build fair teams. Each update only moves one number between the halves.
The story: The Middle Kid
On the first day of school, kids walked into Mrs. Sharma's class one by one. Mira, curious as always, wanted to know after each arrival: "What is the median height now?" The median is the height of the kid standing exactly in the middle if everyone lined up by height. If there is an even number of kids, it is the average of the two middle kids.
Mira's first plan: after every new kid, sort the whole class. With 50 kids that was a lot of lining up. Grandpa Bhaskar suggested, "You do not need the whole line. You only need the two kids in the middle. Split the class into two baskets: the shorter half and the taller half."
The trick: keep the shorter half in a max heap (so its tallest kid is on top) and the taller half in a min heap (so its shortest kid is on top). Those two tops are the kids standing at the middle! Keep the baskets the same size (or the smaller-half basket one bigger), and the median is either the top of the bigger basket, or the average of both tops.
When a kid arrives, pass them through the shorter basket, hand that basket's tallest to the taller basket, and fix any imbalance by moving one kid back. That is the classic running median, using two heaps.
How to spot this problem, and where you need it
You need the middle value of numbers that keep arriving, and recomputing it from scratch with a sort each time is slow and wasteful.
Signs you need it
- A dashboard shows "median" or "typical" value and it lags as data grows.
- You sort the whole list of values every time a new one arrives.
- The task says "find the median from a data stream" or "running median".
Where to use it in a project
- Live dashboards for delivery times, response times, prices or order values.
- Sensor and analytics pipelines where outliers would distort an average.
The solution
Keep two heaps: a max heap for the smaller half and a min heap for the larger half. Add each new number to the correct heap, then rebalance so their sizes differ by at most one. If sizes are equal, the median is the average of the two tops; otherwise it is the top of the bigger heap.
Payoff: Before: re-sorting 100,000 readings on every new one. After: a few heap moves per reading and the median is read in one step.
Explain it like I am 8
Put the shorter half of the class in one basket and the taller half in the other. You only watch two kids: the tallest in the short basket and the shortest in the tall basket. Those two are standing right in the middle, so they tell you the median at once.
How it works, step by step
- Keep a max heap
lowfor the smaller half and a min heaphighfor the bigger half. - Add the new number to
low, then movelow's biggest intohigh. This keeps every number inlownot bigger than every number inhigh. - Balance: if
highhas more items thanlow, move the smallest ofhighback tolow. - The median is the top of
lowwhen the count is odd, or the average of both tops when it is even. - Peeking a median is O(1), and each new number costs a few heap operations.
The code in four languages
PHP
<?php
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before($x, $y) answers: "does x belong closer to the top than y?" (default = min-heap)
class Heap {
private array $a = [];
private $before;
public function __construct(?callable $before = null) {
$this->before = $before ?? fn($x, $y) => $x < $y;
}
public function size(): int { return count($this->a); }
public function peek() { return $this->a[0] ?? null; }
public function push($v): void { // put it at the bottom, then climb
$this->a[] = $v;
$i = count($this->a) - 1;
while ($i > 0) {
$p = intdiv($i - 1, 2);
if (!($this->before)($this->a[$i], $this->a[$p])) break;
[$this->a[$i], $this->a[$p]] = [$this->a[$p], $this->a[$i]];
$i = $p;
}
}
public function pop() { // take the top, put the last one on top, sink it
if (count($this->a) === 0) return null;
$top = $this->a[0];
$last = array_pop($this->a);
$n = count($this->a);
if ($n > 0) {
$this->a[0] = $last;
$i = 0;
while (true) {
$l = 2 * $i + 1; $r = $l + 1; $best = $i;
if ($l < $n && ($this->before)($this->a[$l], $this->a[$best])) $best = $l;
if ($r < $n && ($this->before)($this->a[$r], $this->a[$best])) $best = $r;
if ($best === $i) break;
[$this->a[$i], $this->a[$best]] = [$this->a[$best], $this->a[$i]];
$i = $best;
}
}
return $top;
}
}
// Running median with two heaps.
class MedianFinder {
private Heap $low; // smaller half: a MAX heap (its biggest on top)
private Heap $high; // bigger half: a MIN heap (its smallest on top)
public function __construct() {
$this->low = new Heap(fn($x, $y) => $x > $y);
$this->high = new Heap();
}
public function add(int $x): void {
$this->low->push($x);
$this->high->push($this->low->pop()); // biggest of the small half moves over
if ($this->high->size() > $this->low->size()) { // keep low the same size or one bigger
$this->low->push($this->high->pop());
}
}
public function median() {
if ($this->low->size() > $this->high->size()) return $this->low->peek();
return ($this->low->peek() + $this->high->peek()) / 2;
}
}
$mf = new MedianFinder();
$medians = [];
foreach ([5, 15, 1, 3, 8, 7] as $x) {
$mf->add($x);
$medians[] = $mf->median();
}
echo implode(' ', $medians), PHP_EOL; // 5 10 5 4 5 6JavaScript
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?" (default = min-heap)
class Heap {
constructor(before = (x, y) => x < y) { this.a = []; this.before = before; }
size() { return this.a.length; }
peek() { return this.a[0]; }
push(v) { // put it at the bottom, then climb
const a = this.a; a.push(v);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.before(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]]; i = p;
}
}
pop() { // take the top, put the last one on top, sink it
const a = this.a;
if (a.length === 0) return null;
const top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1; let best = i;
if (l < a.length && this.before(a[l], a[best])) best = l;
if (r < a.length && this.before(a[r], a[best])) best = r;
if (best === i) break;
[a[i], a[best]] = [a[best], a[i]]; i = best;
}
}
return top;
}
}
// Running median with two heaps.
class MedianFinder {
constructor() {
this.low = new Heap((x, y) => x > y); // smaller half: a MAX heap (its biggest on top)
this.high = new Heap(); // bigger half: a MIN heap (its smallest on top)
}
add(x) {
this.low.push(x);
this.high.push(this.low.pop()); // biggest of the small half moves over
if (this.high.size() > this.low.size()) { // keep low the same size or one bigger
this.low.push(this.high.pop());
}
}
median() {
if (this.low.size() > this.high.size()) return this.low.peek();
return (this.low.peek() + this.high.peek()) / 2;
}
}
const mf = new MedianFinder();
const medians = [];
for (const x of [5, 15, 1, 3, 8, 7]) {
mf.add(x);
medians.push(mf.median());
}
console.log(medians.join(' ')); // 5 10 5 4 5 6Java
import java.util.*;
import java.util.function.BiPredicate;
public class Main {
// A heap lives in a plain list. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
static class Heap<T> {
private final List<T> a = new ArrayList<>();
private final BiPredicate<T, T> before;
Heap(BiPredicate<T, T> before) { this.before = before; }
int size() { return a.size(); }
T peek() { return a.isEmpty() ? null : a.get(0); }
void push(T v) { // put it at the bottom, then climb
a.add(v);
int i = a.size() - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (!before.test(a.get(i), a.get(p))) break;
Collections.swap(a, i, p);
i = p;
}
}
T pop() { // take the top, put the last one on top, sink it
if (a.isEmpty()) return null;
T top = a.get(0);
T last = a.remove(a.size() - 1);
int n = a.size();
if (n > 0) {
a.set(0, last);
int i = 0;
while (true) {
int l = 2 * i + 1, r = l + 1, best = i;
if (l < n && before.test(a.get(l), a.get(best))) best = l;
if (r < n && before.test(a.get(r), a.get(best))) best = r;
if (best == i) break;
Collections.swap(a, i, best);
i = best;
}
}
return top;
}
}
// Running median with two heaps.
static class MedianFinder {
private final Heap<Integer> low = new Heap<>((x, y) -> x > y); // smaller half: a MAX heap (its biggest on top)
private final Heap<Integer> high = new Heap<>((x, y) -> x < y); // bigger half: a MIN heap (its smallest on top)
void add(int x) {
low.push(x);
high.push(low.pop()); // biggest of the small half moves over
if (high.size() > low.size()) { // keep low the same size or one bigger
low.push(high.pop());
}
}
double median() {
if (low.size() > high.size()) return low.peek();
return (low.peek() + high.peek()) / 2.0;
}
}
public static void main(String[] args) {
MedianFinder mf = new MedianFinder();
List<String> medians = new ArrayList<>();
for (int x : new int[]{5, 15, 1, 3, 8, 7}) {
mf.add(x);
double m = mf.median();
medians.add(m == Math.floor(m) ? String.valueOf((int) m) : String.valueOf(m));
}
System.out.println(String.join(" ", medians)); // 5 10 5 4 5 6
}
}Go
package main
import (
"fmt"
"strings"
)
// A heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
type Heap[T any] struct {
a []T
before func(x, y T) bool
}
func (h *Heap[T]) Size() int { return len(h.a) }
func (h *Heap[T]) Peek() T { return h.a[0] }
// Push puts it at the bottom, then climbs.
func (h *Heap[T]) Push(v T) {
h.a = append(h.a, v)
i := len(h.a) - 1
for i > 0 {
p := (i - 1) / 2
if !h.before(h.a[i], h.a[p]) {
break
}
h.a[i], h.a[p] = h.a[p], h.a[i]
i = p
}
}
// Pop takes the top, puts the last one on top, and sinks it.
func (h *Heap[T]) Pop() T {
top := h.a[0]
last := h.a[len(h.a)-1]
h.a = h.a[:len(h.a)-1]
n := len(h.a)
if n > 0 {
h.a[0] = last
i := 0
for {
l, r, best := 2*i+1, 2*i+2, i
if l < n && h.before(h.a[l], h.a[best]) {
best = l
}
if r < n && h.before(h.a[r], h.a[best]) {
best = r
}
if best == i {
break
}
h.a[i], h.a[best] = h.a[best], h.a[i]
i = best
}
}
return top
}
// MedianFinder keeps a running median with two heaps.
type MedianFinder struct {
low *Heap[int] // smaller half: a MAX heap (its biggest on top)
high *Heap[int] // bigger half: a MIN heap (its smallest on top)
}
func NewMedianFinder() *MedianFinder {
return &MedianFinder{
low: &Heap[int]{before: func(x, y int) bool { return x > y }},
high: &Heap[int]{before: func(x, y int) bool { return x < y }},
}
}
func (m *MedianFinder) Add(x int) {
m.low.Push(x)
m.high.Push(m.low.Pop()) // biggest of the small half moves over
if m.high.Size() > m.low.Size() { // keep low the same size or one bigger
m.low.Push(m.high.Pop())
}
}
func (m *MedianFinder) Median() float64 {
if m.low.Size() > m.high.Size() {
return float64(m.low.Peek())
}
return float64(m.low.Peek()+m.high.Peek()) / 2
}
func main() {
mf := NewMedianFinder()
var medians []float64
for _, x := range []int{5, 15, 1, 3, 8, 7} {
mf.Add(x)
medians = append(medians, mf.Median())
}
fmt.Println(strings.Trim(fmt.Sprint(medians), "[]")) // 5 10 5 4 5 6
}Time: O(log n) per number, O(1) to read the median · Extra space: O(n). Every number lives in one of the two heaps; each arrival does a handful of pushes and pops.
Watch out for
- Putting the new number straight into either heap without checking, which can put a bigger number in the smaller half.
- Letting the two heaps drift apart in size. They must differ by at most one, or the tops are not the middle.
- Using two min heaps. The smaller half needs a max heap so that its largest is on top.
Quick check
- Which two heaps are used?
- Two min heaps
- A max heap for the smaller half and a min heap for the bigger half
- A min heap for the smaller half and a max heap for the bigger half
- With an even number of values, the median is...
- The average of the two tops
- The top of the high heap
- The top of the low heap
- How long does it take to read the current median?
- O(n)
- O(1)
- O(log n)