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

Four Sum visualizer

Learn Four Sum with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 8Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    0,
    -1,
    0,
    -2,
    2
  ],
  "k": 0,
  "n": 4
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,n
},s)=>{
a.sort((x,y)=>x-y);
let o=[];
function f(start,k,n,p){
if(n===2){
let l=start,r=a.length-1;
while(l<r){
let t=a[l]+a[r];
s("Compare remaining pair",{
Array:a,Prefix:p,Matches:o
},[l,r]);
if(t===k){
o.push([...p,a[l],a[r]]);
let x=a[l],y=a[r];
while(l<r&&a[l]===x)l++;
while(l<r&&a[r]===y)r--
}else if(t<k)l++;
else r--
}
return
}
for(let i=start;
i<=a.length-n;
i++)if(i===start||a[i]!==a[i-1])f(i+1,k-a[i],n-1,[...p,a[i]])
}
f(0,k,n,[]);
return o
};

Execution canvas

Active Changed
STEP 1

Compare remaining pair

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

Array6 items
Prefix2 items
Matches0 items

Empty at this step.

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

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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,
    0,
    -1,
    0,
    -2,
    2
  ],
  "k": 0,
  "n": 4
}

Execution steps

  1. Compare remaining pair

Computed output

[
  [
    -2,
    -1,
    1,
    2
  ],
  [
    -2,
    0,
    0,
    2
  ],
  [
    -1,
    0,
    0,
    1
  ]
]
JavaScript reference implementation
const solve = ({
  a,k,n
},s)=>{
  a.sort((x,y)=>x-y);
  let o=[];
  function f(start,k,n,p){
    if(n===2){
      let l=start,r=a.length-1;
      while(l<r){
        let t=a[l]+a[r];
        s("Compare remaining pair",{
          Array:a,Prefix:p,Matches:o
        },[l,r]);
        if(t===k){
          o.push([...p,a[l],a[r]]);
          let x=a[l],y=a[r];
          while(l<r&&a[l]===x)l++;
          while(l<r&&a[r]===y)r--
        }else if(t<k)l++;
        else r--
      }
      return
    }
    for(let i=start;
    i<=a.length-n;
    i++)if(i===start||a[i]!==a[i-1])f(i+1,k-a[i],n-1,[...p,a[i]])
  }
  f(0,k,n,[]);
  return o
};

Continue learning

Practice related DSA questions in the same topic.