https://leetcode.com/problems/binary-subarrays-with-sum/
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186683/C%2B%2BJavaPython-Straight-Forward
https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186647/Java-Clean-Solution-2-Sum-%2B-Prefix-Sum-Caching
In an array
A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]
Approach 3: Three Pointer
For each
j
, let's try to count the number of i
's that have the subarray [i, j]
equal to S
.
It is easy to see these
i
's form an interval [i_lo, i_hi]
, and each of i_lo
, i_hi
are increasing with respect to j
. So we can use a "two pointer" style approach.
Algorithm
For each
j
(in increasing order), let's maintain 4 variables:sum_lo
: the sum of subarray[i_lo, j]
sum_hi
: the sum of subarray[i_hi, j]
i_lo
: the smallesti
so thatsum_lo <= S
i_hi
: the largesti
so thatsum_hi <= S
Then, (provided that
sum_lo == S
), the number of subarrays ending in j
is i_hi - i_lo + 1
.
As an example, with
A = [1,0,0,1,0,1]
and S = 2
, when j = 5
, we want i_lo = 1
and i_hi = 3
.
public int numSubarraysWithSum(int[] A, int S) {
int iLo = 0, iHi = 0;
int sumLo = 0, sumHi = 0;
int ans = 0;
for (int j = 0; j < A.length; ++j) {
// While sumLo is too big, iLo++
sumLo += A[j];
while (iLo < j && sumLo > S)
sumLo -= A[iLo++];
// While sumHi is too big, or equal and we can move, iHi++
sumHi += A[j];
while (iHi < j && (sumHi > S || sumHi == S && A[iHi] == 0))
sumHi -= A[iHi++];
if (sumLo == S)
ans += iHi - iLo + 1;
}
return ans;
}
Approach 2: Prefix Sums
Intuition
Let
P[i] = A[0] + A[1] + ... + A[i-1]
. Then P[j+1] - P[i] = A[i] + A[i+1] + ... + A[j]
, the sum of the subarray [i, j]
.
Hence, we are looking for the number of
i < j
with P[j] - P[i] = S
.
Algorithm
For each
j
, let's count the number of i
with P[j] = P[i] + S
. This is analogous to counting the number of subarrays ending in j
with sum S
.
It comes down to counting how many
P[i] + S
we've seen before. We can keep this count on the side to help us find the final answer.
public int numSubarraysWithSum(int[] A, int S) {
int N = A.length;
int[] P = new int[N + 1];
for (int i = 0; i < N; ++i)
P[i + 1] = P[i] + A[i];
Map<Integer, Integer> count = new HashMap();
int ans = 0;
for (int x : P) {
ans += count.getOrDefault(x, 0);
count.put(x + S, count.getOrDefault(x + S, 0) + 1);
}
return ans;
}
public int numSubarraysWithSum(int[] A, int S) {
int psum = 0, res = 0, count[] = new int[A.length + 1];
count[0] = 1;
for (int i : A) {
psum += i;
if (psum >= S)
res += count[psum - S];
count[psum]++;
}
return res;
}
Using a hashmap is overkill in this problem since the only sums that are possible are [0, 1, ..., n].
Therefore, we can just an array as our map instread. Credits to @davidluoyes for pointing this out.
Therefore, we can just an array as our map instread. Credits to @davidluoyes for pointing this out.
public int numSubarraysWithSum(int[] A, int target) {
//The largest sum we can have is len(A) = n Why? What if array A[] has all 1's.
int n = A.length;
//Everything is initialized to zero
int[] presum = new int[n+1];
int sum = 0;
//Case where it's just it's own
int total = 0;
for (int i = 0; i < A.length; i++){
sum += A[i];
int compliment = sum - target;
if (compliment >= 0)
total += presum[compliment];
if (sum == target) total++;
//Also put this sum into the map as well
presum[sum]+=1;
}
return total;
}
TLDR; Two Sum + Prefix Sum Caching
Logic:
In this problem we are required to find some interval [i:j] ,i < j
where sum[i:j] = target
. We know that sum[i:j] = A[i] + A[i+1] +... + A[j]
.
Then we also know that
Let's define prefixSum[j] = A[0] + A[1] + ... + A[j] 0 <= j <= n-1 (n = A.length)
It is easy to see that,
sum[i:j] = A[i] + A[i+1] ... + A[j] =
(A[0] + A[1] + ... A[i] ... + A[j]) - (A[0] + A[1] + ... A[i-1])
=
prefix[j] - prefix[i-1]
.
Now we the problem reduces to finding # of pairs (i, j) (i < j) such that
prefix[j] - prefix[i-1]
= target
This becomes prefix[i-1] = prefix[j] - target with some algebra.
So we use the hashmap to find all pairs that satisfy the above equations.
We only need to track the prefix sum up to this point however, since we already saved all the previous results in the map.
if (sum == target) total++
Here I am checking for the case where the current element is equal to the sum (it needs no interval to produce the sum).
public int numSubarraysWithSum(int[] A, int target) {
Map<Integer, Integer> presum = new HashMap<>();
//Prefix sum
int sum = 0;
//Answer
int total = 0;
for (int i = 0; i < A.length; i++){
sum += A[i];
if (presum.get(sum - target) != null){
total += presum.get(sum - target);
}
if (sum == target) total++;
//Also put this sum into the map as well
presum.put(sum, presum.getOrDefault(sum, 0) + 1);
}
return total;
}
Approach 1: Index of Ones
Intuition
Say we number the
1
s in A
: with .
Then, if we have a subarray of sum , it has to use the ones . For each , we can count the number of such subarrays individually.
Algorithm
In general, the number of such subarrays (for ) is .
For example, if , then in
A = [1,0,1,0,1,0,0,1]
, let's count the number of subarrays [i, j]
that use the middle two 1
s. There are 2 choices for the i
(i = 1, 2)
and 3 choices for the j
(j = 4, 5, 6)
.
The corner cases are when , , or . We can handle these gracefully.
public int numSubarraysWithSum(int[] A, int S) {
int su = 0;
for (int x : A)
su += x;
// indexes[i] = location of i-th one (1 indexed)
int[] indexes = new int[su + 2];
int t = 0;
indexes[t++] = -1;
for (int i = 0; i < A.length; ++i)
if (A[i] == 1)
indexes[t++] = i;
indexes[t] = A.length;
int ans = 0;
if (S == 0) {
for (int i = 0; i < indexes.length - 1; ++i) {
// w: number of zeros between consecutive ones
int w = indexes[i + 1] - indexes[i] - 1;
ans += w * (w + 1) / 2;
}
return ans;
}
for (int i = 1; i < indexes.length - S; ++i) {
int j = i + S - 1;
int left = indexes[i] - indexes[i - 1];
int right = indexes[j + 1] - indexes[j];
ans += left * right;
}
return ans;
}