Workspace Expression Add Operators
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Expression Add Operators visualizer

Learn Expression Add Operators with a step-by-step Recursion & Backtracking visualizer, JavaScript source code and a worked example. Practice constraint search.

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 / 23Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": "123",
  "target": 6
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,target
},s)=>{
let o=[];
function f(i,p,v,last){
s("Explore expression",{
Expression:[p],Value:[v],Solutions:o
});
if(i===a.length){
if(v===target)o.push(p);
return
}
for(let j=i+1;
j<=a.length;
j++){
if(j>i+1&&a[i]==="0")break;
let w=a.slice(i,j),x=+w;
if(!i)f(j,w,x,x);
else{
f(j,p+"+"+w,v+x,x);
f(j,p+"-"+w,v-x,-x);
f(j,p+"*"+w,v-last+last*x,last*x)
}
}
}
f(0,"",0,0);
return o
};

Execution canvas

Active Changed
STEP 1

Explore expression

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

Expression1 items
Value1 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 · Constraint search

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": "123",
  "target": 6
}

Execution steps

  1. Explore expression

Computed output

[
  "1+2+3",
  "1*2*3"
]
JavaScript reference implementation
const solve = ({
  a,target
},s)=>{
  let o=[];
  function f(i,p,v,last){
    s("Explore expression",{
      Expression:[p],Value:[v],Solutions:o
    });
    if(i===a.length){
      if(v===target)o.push(p);
      return
    }
    for(let j=i+1;
    j<=a.length;
    j++){
      if(j>i+1&&a[i]==="0")break;
      let w=a.slice(i,j),x=+w;
      if(!i)f(j,w,x,x);
      else{
        f(j,p+"+"+w,v+x,x);
        f(j,p+"-"+w,v-x,-x);
        f(j,p+"*"+w,v-last+last*x,last*x)
      }
    }
  }
  f(0,"",0,0);
  return o
};

Continue learning

Practice related DSA questions in the same topic.