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

Combination Sum III visualizer

Learn Combination Sum III with a step-by-step Recursion & Backtracking visualizer, JavaScript source code and a worked example. Practice subsets and combinations.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,reuse,len
},s)=>{
a.sort((x,y)=>x-y);
let o=[];
function f(i,k,p){
s("Explore combination",{
Candidates:a,Path:p,Remaining:[k],Solutions:o
});
if(!k){
if(!len||p.length===len)o.push(p);
return
}
if(len&&p.length===len)return;
for(let j=i;
j<a.length&&a[j]<=k;
j++)if(j===i||a[j]!==a[j-1])f(reuse?j:j+1,k-a[j],[...p,a[j]])
}
f(0,k,[]);
return o
};

Execution canvas

Active Changed
STEP 1

Explore combination

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

Candidates9 items
Path0 items

Empty at this step.

Remaining1 items
Solutions0 items

Empty at this step.

Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Recursion & Backtracking · Subsets and combinations

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
  ],
  "k": 7,
  "reuse": false,
  "len": 3
}

Execution steps

  1. Explore combination

Computed output

[
  [
    1,
    2,
    4
  ]
]
JavaScript reference implementation
const solve = ({
  a,k,reuse,len
},s)=>{
  a.sort((x,y)=>x-y);
  let o=[];
  function f(i,k,p){
    s("Explore combination",{
      Candidates:a,Path:p,Remaining:[k],Solutions:o
    });
    if(!k){
      if(!len||p.length===len)o.push(p);
      return
    }
    if(len&&p.length===len)return;
    for(let j=i;
    j<a.length&&a[j]<=k;
    j++)if(j===i||a[j]!==a[j-1])f(reuse?j:j+1,k-a[j],[...p,a[j]])
  }
  f(0,k,[]);
  return o
};

Continue learning

Practice related DSA questions in the same topic.