Data Structures19 sections · 729 units
Open in Course

The Median Problem

Running median challenge

Given a stream of numbers, find the median at any point. The median is the middle element. For odd count, it's the center.

For even count, it's the average of the two center elements. Challenge: after each insertion, you need the median in O(1)O(1) time.

Sorting after each insertion is O(nlogn)O(n \log n), too slow. A clever technique uses two heaps to maintain O(logn)O(\log n) insertion with O(1)O(1) median queries.