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