Workspace Binary Subarrays With Sum
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Binary Subarrays With Sum visualizer

Learn Binary Subarrays With Sum with a step-by-step Sliding Window & Two Pointers visualizer, JavaScript source code and a worked example. Practice fixed and variable windows.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,odd
},s)=>{
let m=new Map([[0,1]]),p=0,c=0;
for(let i=0;
i<a.length;
i++){
p+=odd?a[i]%2:a[i];
c+=m.get(p-k)||0;
m.set(p,(m.get(p)||0)+1);
s("Match earlier prefix",{
Array:a,Prefix:[p],Count:[c]
},[i])
}
return c
};

Execution canvas

Active Changed
STEP 1

Match earlier prefix

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

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

Worked example and algorithm walkthrough

Topic: Sliding Window & Two Pointers · Fixed and variable windows

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

Execution steps

  1. Match earlier prefix

Computed output

4
JavaScript reference implementation
const solve = ({
  a,k,odd
},s)=>{
  let m=new Map([[0,1]]),p=0,c=0;
  for(let i=0;
  i<a.length;
  i++){
    p+=odd?a[i]%2:a[i];
    c+=m.get(p-k)||0;
    m.set(p,(m.get(p)||0)+1);
    s("Match earlier prefix",{
      Array:a,Prefix:[p],Count:[c]
    },[i])
  }
  return c
};

Continue learning

Practice related DSA questions in the same topic.