Binary Subarrays With Sum

Count 0/1 subarrays summing to goal — atMost(goal) − atMost(goal−1).

Medium
Time O(n) Space O(1)
LeetCode
3 min read
sliding-window array

Problem#

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

Examples#

  • nums = [1,0,1,0,1], goal = 24
  • nums = [0,0,0,0,0], goal = 015

Constraints#

  • 1 <= nums.length <= 3 * 10^4, goal <= sum(nums).

Approach#

Same exact-vs-atmost trick: exact(goal) = atMost(goal) − atMost(goal − 1). atMost(g) is a clean sliding window over binary values.

Solution#

Binary Subarrays With Sum
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
return atMost(nums, goal) - atMost(nums, goal - 1);
}
private:
int atMost(vector<int>& nums, int g) {
if (g < 0) return 0;
int left = 0, sum = 0, ans = 0;
for (int right = 0; right < (int)nums.size(); ++right) {
sum += nums[right];
while (sum > g) sum -= nums[left++];
ans += right - left + 1;
}
return ans;
}
};

Editorial#

The presence of zeros prevents the naïve sliding window from working for “exactly K” — zeros can be padded indefinitely. The atMost difference reduction reduces both cases to monotone windows, which handle zeros naturally.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.