Workspace Kth Largest Element In An Array
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Kth Largest Element in an Array visualizer

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,large
},s)=>{
let heap=[];
const cmp=(x,y)=>large?x<y:x>y;
function push(x){
heap.push(x);
let i=heap.length-1;
while(i){
let p=(i-1)>>1;
if(!cmp(heap[i],heap[p]))break;
[heap[i],heap[p]]=[heap[p],heap[i]];
i=p
}
}
function pop(){
let v=heap.pop();
if(!heap.length)return;
heap[0]=v;
let i=0;
while(true){
let l=2*i+1,r=l+1,b=i;
if(l<heap.length&&cmp(heap[l],heap[b]))b=l;
if(r<heap.length&&cmp(heap[r],heap[b]))b=r;
if(b===i)break;
[heap[i],heap[b]]=[heap[b],heap[i]];
i=b
}
}
for(let x of a){
push(x);
if(heap.length>k)pop();
s("Keep best k elements in heap",{
Input:a,Heap:heap
})
}
return heap[0]
};

Execution canvas

Active Changed
STEP 1

Keep best k elements in heap

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

Input6 items
Heap1 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": [
    3,
    2,
    1,
    5,
    6,
    4
  ],
  "k": 2,
  "large": true
}

Execution steps

  1. Keep best k elements in heap

Computed output

5
JavaScript reference implementation
const solve = ({
  a,k,large
},s)=>{
  let heap=[];
  const cmp=(x,y)=>large?x<y:x>y;
  function push(x){
    heap.push(x);
    let i=heap.length-1;
    while(i){
      let p=(i-1)>>1;
      if(!cmp(heap[i],heap[p]))break;
      [heap[i],heap[p]]=[heap[p],heap[i]];
      i=p
    }
  }
  function pop(){
    let v=heap.pop();
    if(!heap.length)return;
    heap[0]=v;
    let i=0;
    while(true){
      let l=2*i+1,r=l+1,b=i;
      if(l<heap.length&&cmp(heap[l],heap[b]))b=l;
      if(r<heap.length&&cmp(heap[r],heap[b]))b=r;
      if(b===i)break;
      [heap[i],heap[b]]=[heap[b],heap[i]];
      i=b
    }
  }
  for(let x of a){
    push(x);
    if(heap.length>k)pop();
    s("Keep best k elements in heap",{
      Input:a,Heap:heap
    })
  }
  return heap[0]
};

Continue learning

Practice related DSA questions in the same topic.