Practice › Sliding Window
Binary Subarrays with Given Sum
Medium · Sliding Window · Asked at Google, Amazon, Microsoft
The array contains only 0s and 1s. Print how many non-empty contiguous subarrays have sum exactly goal.
Input
First line: n goal. Second line: n values (0 or 1).
Output
The number of subarrays.
Constraints
- 1 ≤ n ≤ 10^5
- 0 ≤ goal ≤ n
atMost(g) = number of subarrays with sum ≤ g, found with a sliding window. Then exactly(goal) = atMost(goal) − atMost(goal − 1). A prefix-sum count in a hash map works too. The answer can pass 2^31.
Example 1
Input
5 2 1 0 1 0 1
Output
4
Example 2
Input
5 0 0 0 0 0 0
Output
15
Hints
- A subarray (i, j] has sum P[j] − P[i] where P are prefix sums.
- So count earlier prefixes equal to P[j] − goal.
- Prefix sums of a 0/1 array are at most n — an array works as the counter.
Approach
Keep cnt[v] = number of prefixes seen with sum v (cnt[0] = 1 for the empty prefix). For each element, update the running prefix P and add cnt[P − goal] if that index is valid, then increment cnt[P]. This handles goal = 0 correctly (runs of zeros), which a plain sliding window does not. The answer can be about n² / 2, so use 64 bits.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, goal;
cin >> n >> goal;
vector<long long> cnt(n + 1, 0);
cnt[0] = 1;
int pre = 0;
long long res = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
pre += x;
if (pre - goal >= 0) res += cnt[pre - goal];
cnt[pre]++;
}
cout << res << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, goal = data[0], data[1]
cnt = [0] * (n + 1)
cnt[0] = 1
pre = res = 0
for x in data[2 : 2 + n]:
pre += x
if pre >= goal:
res += cnt[pre - goal]
cnt[pre] += 1
print(res)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int goal = (int) in.nval;
long[] cnt = new long[n + 1];
cnt[0] = 1;
int pre = 0;
long res = 0;
for (int i = 0; i < n; i++) {
in.nextToken();
pre += (int) in.nval;
if (pre - goal >= 0) res += cnt[pre - goal];
cnt[pre]++;
}
System.out.println(res);
}
}Solve Binary Subarrays with Given Sum online · All practice problems