Workspace Subarray Sum Equals K
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Subarray Sum Equals K visualizer

Learn Subarray Sum Equals K with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice hashing and prefix sums.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let m=new Map([[0,1]]),v=0,c=0;
a.forEach((x,i)=>{
v+=x;
c+=m.get(v-k)||0;
m.set(v,(m.get(v)||0)+1);
s("Look up matching prefix",{
Array:a,Prefix:[v],Count:[c],Map:[...m].map(x=>x.join(":"))
},[i])
});
return c
};

Execution canvas

Active Changed
STEP 1

Look up matching prefix

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

Array4 items
Prefix1 items
Count1 items
Map2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Hashing and prefix sums

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

Execution steps

  1. Look up matching prefix

Computed output

3
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let m=new Map([[0,1]]),v=0,c=0;
  a.forEach((x,i)=>{
    v+=x;
    c+=m.get(v-k)||0;
    m.set(v,(m.get(v)||0)+1);
    s("Look up matching prefix",{
      Array:a,Prefix:[v],Count:[c],Map:[...m].map(x=>x.join(":"))
    },[i])
  });
  return c
};

Continue learning

Practice related DSA questions in the same topic.