Workspace Capacity To Ship Packages
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Capacity to Ship Packages visualizer

Learn Capacity to Ship Packages 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 / 6Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
  ],
  "k": 5,
  "mode": "pack"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,mode
},s)=>{
let l=mode==="ceil"?1:Math.max(...a),r=mode==="ceil"?Math.max(...a):a.reduce((x,y)=>x+y,0);
while(l<r){
let m=Math.floor((l+r)/2),used=0;
if(mode==="ceil")used=a.reduce((x,y)=>x+Math.ceil(y/m),0);
else{
used=1;
let sum=0;
for(let x of a){
if(sum+x>m){
used++;
sum=0
}
sum+=x
}
}
s("Test capacity "+m,{
Input:a,Bounds:[l,m,r],Required:[used],Limit:[k]
});
if(used<=k)r=m;
else l=m+1
}
return l
};

Execution canvas

Active Changed
STEP 1

Test capacity 32

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

Input10 items
Bounds3 items
Required1 items
Limit1 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,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
  ],
  "k": 5,
  "mode": "pack"
}

Execution steps

  1. Test capacity 32
  2. Test capacity 21
  3. Test capacity 15
  4. Test capacity 12
  5. Test capacity 14

Computed output

15
JavaScript reference implementation
const solve = ({
  a,k,mode
},s)=>{
  let l=mode==="ceil"?1:Math.max(...a),r=mode==="ceil"?Math.max(...a):a.reduce((x,y)=>x+y,0);
  while(l<r){
    let m=Math.floor((l+r)/2),used=0;
    if(mode==="ceil")used=a.reduce((x,y)=>x+Math.ceil(y/m),0);
    else{
      used=1;
      let sum=0;
      for(let x of a){
        if(sum+x>m){
          used++;
          sum=0
        }
        sum+=x
      }
    }
    s("Test capacity "+m,{
      Input:a,Bounds:[l,m,r],Required:[used],Limit:[k]
    });
    if(used<=k)r=m;
    else l=m+1
  }
  return l
};

Continue learning

Practice related DSA questions in the same topic.