backbenchcode
← all problemsnext: Top K Frequent Elements
#10HardFrom Research to FAANG · 35% acceptance

Median of a Data Stream

HeapDesignTwo Heaps

Design a structure that ingests numbers one at a time and can report the median of everything seen so far at any moment.

Running statistics over a live stream — you have done this on instrument output. The elegant answer is two heaps.

Examples

Input: add(1); add(2); median(); add(3); median()

Output: 1.5, then 2

Constraints

Hints

solution.pyPython 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Test console

// hit Run to execute the sample tests

// Interactive editor preview. Live code execution arrives with your early-access cohort.