393. Binary Subarrays With Sum

Given a binary array nums and an integer goal. Return the number of non-empty subarrays with a sum goal.

A subarray is a continuous part of the array.

Example 1:

Input : nums = [1, 1, 0, 1, 0, 0, 1] , goal = 3

Output : 4

Explanation : The subarray with sum 3 are

[1, 1, 0, 1]

[1, 1, 0, 1, 0]

[1, 1, 0, 1, 0, 0]

[1, 0, 1, 0, 0, 1].

Now Your Turn!

Pick the correct output for the given input

Input : nums = [0, 0, 0, 0, 1] , goal = 0

Output : 10

Explanation : Some of the subarray with sum 0 are

[0]

[0, 0]

[0, 0, 0]

[0, 0, 0, 0]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 3*104
  • 0 <= goal <= nums.length
  • nums consist of only 0 and 1.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
//your code goes here
}
};
Test Case

Input:

Goal
Nums