Workspace Kth Largest Element In A Stream
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Kth Largest Element in a Stream visualizer

Learn Kth Largest Element in a 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 / 6Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    4,
    5,
    8,
    2
  ],
  "stream": [
    3,
    5,
    10,
    9,
    4
  ],
  "k": 3
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,stream,k
},s)=>{
let h=a.sort((a,b)=>b-a).slice(0,k),o=[];
for(let x of stream){
h.push(x);
h.sort((a,b)=>b-a);
h=h.slice(0,k);
o.push(h.at(-1));
s("Keep largest k values",{
Top:h,Output:o
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Keep largest k values

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

Top3 items
Output1 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

{
  "a": [
    4,
    5,
    8,
    2
  ],
  "stream": [
    3,
    5,
    10,
    9,
    4
  ],
  "k": 3
}

Execution steps

  1. Keep largest k values

Computed output

[
  4,
  5,
  5,
  8,
  8
]
JavaScript reference implementation
const solve = ({
  a,stream,k
},s)=>{
  let h=a.sort((a,b)=>b-a).slice(0,k),o=[];
  for(let x of stream){
    h.push(x);
    h.sort((a,b)=>b-a);
    h=h.slice(0,k);
    o.push(h.at(-1));
    s("Keep largest k values",{
      Top:h,Output:o
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.