Workspace Subset Sum
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Subset Sum visualizer

Learn Subset Sum with a step-by-step Dynamic Programming visualizer, JavaScript source code and a worked example. Practice subsequences and knapsack.

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,
    34,
    4,
    12,
    5,
    2
  ],
  "k": 9,
  "mode": "exists"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,mode
},s)=>{
let d=Array(k+1).fill(0);
d[0]=1;
for(let x of a){
for(let j=k;
j>=x;
j--)d[j]+=d[j-x];
s("Include or exclude current value",{
Input:a,DP:d,Value:[x]
})
}
if(mode==="exists")return d[k]>0;
if(mode==="count")return d[k];
let j=k;
while(!d[j])j--;
return a.reduce((x,y)=>x+y,0)-2*j
};

Execution canvas

Active Changed
STEP 1

Include or exclude current value

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

Input6 items
DP10 items
Value1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Dynamic Programming · Subsequences and knapsack

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,
    34,
    4,
    12,
    5,
    2
  ],
  "k": 9,
  "mode": "exists"
}

Execution steps

  1. Include or exclude current value

Computed output

true
JavaScript reference implementation
const solve = ({
  a,k,mode
},s)=>{
  let d=Array(k+1).fill(0);
  d[0]=1;
  for(let x of a){
    for(let j=k;
    j>=x;
    j--)d[j]+=d[j-x];
    s("Include or exclude current value",{
      Input:a,DP:d,Value:[x]
    })
  }
  if(mode==="exists")return d[k]>0;
  if(mode==="count")return d[k];
  let j=k;
  while(!d[j])j--;
  return a.reduce((x,y)=>x+y,0)-2*j
};

Continue learning

Practice related DSA questions in the same topic.