Workspace Generate Binary Strings
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Generate Binary Strings visualizer

Learn Generate Binary Strings 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 / 12Execution step
Reference example · JavaScript
Inspect reference input
{
  "n": 3,
  "paren": false
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
n,paren
},s)=>{
let o=[];
function f(p,l,r){
s("Explore prefix",{
Prefix:[...p],Solutions:o
});
if(p.length===(paren?2*n:n)){
o.push(p);
return
}
if(paren){
if(l<n)f(p+"(",l+1,r);
if(r<l)f(p+")",l,r+1)
}else{
f(p+"0",0,0);
if(!p.endsWith("1"))f(p+"1",0,0)
}
}
f("",0,0);
return o
};

Execution canvas

Active Changed
STEP 1

Explore prefix

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

Prefix0 items

Empty at this step.

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

{
  "n": 3,
  "paren": false
}

Execution steps

  1. Explore prefix

Computed output

[
  "000",
  "001",
  "010",
  "100",
  "101"
]
JavaScript reference implementation
const solve = ({
  n,paren
},s)=>{
  let o=[];
  function f(p,l,r){
    s("Explore prefix",{
      Prefix:[...p],Solutions:o
    });
    if(p.length===(paren?2*n:n)){
      o.push(p);
      return
    }
    if(paren){
      if(l<n)f(p+"(",l+1,r);
      if(r<l)f(p+")",l,r+1)
    }else{
      f(p+"0",0,0);
      if(!p.endsWith("1"))f(p+"1",0,0)
    }
  }
  f("",0,0);
  return o
};

Continue learning

Practice related DSA questions in the same topic.