Binary Subarrays With Sum

Given a binary array `nums` and an integer `goal`, return the number of non-empty subarrays with a sum equal to `goal`. A subarray is a contiguous part of the array.

30:00

Binary Subarrays With Sum
medium
Free written solution
Topics
Companies

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum equal to goal.

A subarray is a contiguous part of the array.

Example 1:
Input: {"nums":[1,0,1,0,1],"goal":2}
Output: 4
Constraints:
  • 1≤nums.length≤3×1041 \leq \text{nums.length} \leq 3 \times 10^4

  • nums[i]\text{nums}[i] is either 00 or 11

  • 0≤goal≤nums.length0 \leq \text{goal} \leq \text{nums.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,0,1,0,1],"goal":2}

For each right end, the starts that give sum 2 form one band [lo, hi). Two left pointers track its edges.

goal = 2

1
0
1
0
1

0

1

2

3

4

sum from lo

-

sum from hi

-

band hi - lo

-

count

0

Variables
VariableValue
lo0
hi0
count0
goal2
DepthFunction Call
Stack empty
0/15