Workspace Aggressive Cows
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Aggressive Cows visualizer

Learn Aggressive Cows with a step-by-step Binary Search visualizer, JavaScript source code and a worked example. Practice search on answer.

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 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    2,
    4,
    8,
    9
  ],
  "k": 3
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
a.sort((x,y)=>x-y);
let l=1,r=a.at(-1)-a[0],b=0;
while(l<=r){
let m=(l+r)>>1,p=[a[0]];
for(let x of a.slice(1))if(x-p.at(-1)>=m)p.push(x);
s("Test separation "+m,{
Stalls:a,Placed:p,Bounds:[l,m,r]
});
if(p.length>=k){
b=m;
l=m+1
}else r=m-1
}
return b
};

Execution canvas

Active Changed
STEP 1

Test separation 4

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

Stalls5 items
Placed2 items
Bounds3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Binary Search · Search on answer

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": [
    1,
    2,
    4,
    8,
    9
  ],
  "k": 3
}

Execution steps

  1. Test separation 4
  2. Test separation 2
  3. Test separation 3

Computed output

3
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  a.sort((x,y)=>x-y);
  let l=1,r=a.at(-1)-a[0],b=0;
  while(l<=r){
    let m=(l+r)>>1,p=[a[0]];
    for(let x of a.slice(1))if(x-p.at(-1)>=m)p.push(x);
    s("Test separation "+m,{
      Stalls:a,Placed:p,Bounds:[l,m,r]
    });
    if(p.length>=k){
      b=m;
      l=m+1
    }else r=m-1
  }
  return b
};

Continue learning

Practice related DSA questions in the same topic.