Workspace Find Median From Data Stream
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Find Median from Data Stream visualizer

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.

1 / 5Execution step
Reference example · JavaScript
Inspect reference input
[
  1,
  2,
  3,
  4
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
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
};

Execution canvas

Active Changed
STEP 1

Rebalance lower and upper halves

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Lower1 items
Upper0 items

Empty at this step.

Medians1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Heaps · Priority queues and top K

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

  1. 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
};

Continue learning

Practice related DSA questions in the same topic.