In our telemetry service, financial tick prices arrive at ~10,000 events/second. We need an online algorithm that can output the exact running median at any moment.
Sorting the buffer on every tick is O(N log N), which is impossible at high frequency. What is the standard dual-heap architecture used to maintain running medians in real time?
The classic, production-proven design for calculating running medians is the Dual-Heap Balancing Architecture (one Max-Heap and one Min-Heap).
1. The Mental Model
Imagine splitting all numbers you’ve seen so far into two equal halves:
The median is ALWAYS right at the fingertips: either the top of the Max-Heap, or the average of the two tops!
2. The Two Golden Invariants
To make this work 100% reliably, you must maintain two invariants after every single number is added:
max_heapmust be $le$ every element inmin_heap. (Ifmax_heap.top() > min_heap.top(), swap them).0 <= len(max_heap) - len(min_heap) <= 1.Production Python 3.12 Implementation
Performance & Production Benchmarks
O(log N). Pushing and popping from heaps of sizeN/2takes ~15-20 CPU instructions.O(1). Simply peek at heap roots (index 0). Instantaneous!O(N)total memory to store the incoming stream numbers.Here is the clean C++20 Dual-Heap solution using
std::priority_queuewithstd::greater<int>for the min-heap. This providesO(log N)insertion andO(1)median query.Complexity:
O(log N)per tick andO(1)for median queries.