Learn Find Median from Data Stream with a step-by-step Heaps visualizer, JavaScript source code and a worked example. Practice priority queues and top k.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
[
1,
2,
3,
4
]
Execution steps
Rebalance lower and upper halves
Computed output
[
1,
1.5,
2,
2.5
]
JavaScript reference implementation
const solve = (a,s)=>{
let l=[],r=[],o=[];
for(let x of a){
if(!l.length||x<=l.at(-1)){
l.push(x);
l.sort((a,b)=>a-b)
}else{
r.push(x);
r.sort((a,b)=>a-b)
}
if(l.length>r.length+1)r.unshift(l.pop());
if(r.length>l.length)l.push(r.shift());
o.push(l.length===r.length?(l.at(-1)+r[0])/2:l.at(-1));
s("Rebalance lower and upper halves",{
Lower:l,Upper:r,Medians:o
})
}
return o
};