Workspace Count Subsets With Sum K
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Count Subsets with Sum K visualizer

Learn Count Subsets with Sum K 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 / 5Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    2,
    2,
    3
  ],
  "k": 3,
  "mode": "count"
}

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.

Input4 items
DP4 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": [
    1,
    2,
    2,
    3
  ],
  "k": 3,
  "mode": "count"
}

Execution steps

  1. Include or exclude current value

Computed output

3
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.