Question: check if there is a subarray sum equals to the given target.
This question should ask for clarifications. Whether the inputs are all positive, or it has negative numbers.
1: If all the numbers are positive, we can just use two pointers way:
bool checkSubarraySum(vector<int>& array, int target) {
int sum = 0;
int i = 0, j = 0;
while(i < array.size()) {
sum += array[i];
while(j < i && sum > target) {
sum -= array[j];
j++;
}
if(target == sum) return true;
i++;
}
return false;
}
2: if there is any negative numbers, can't use this way anymore, instead, we need to dynamic programming idea.
bool checkSubarraySumWithNegative(vector<int>& array, int target) {
for(int i = 1; i < array.size(); ++i) {
array[i] += array[i-1];
}
set<int> sums;
sums.insert(0);
for(int i = 0; i < array.size(); ++i) {
if(sums.count(target - array[i])) return true;
sums.insert(array[i]);
}
return false;
}
// now, extend it to a 2d array. check if there is any rectangle that sums to a given target.
bool checkMatrix(vector< vector<int> >& matrix, int target) {
for(int i = 1; i < matrix.size(); ++i) {
matrix[i][0] += matrix[i-1][0];
}
for(int j = 1; j < matrix[0].size(); ++j) {
matrix[0][j] += matrix[0][j-1];
}
for(int i = 1; i < matrix.size(); ++i) {
for(int j = 1; j < matrix[0].size(); ++j) {
matrix[i][j] += matrix[i-1][j] + matrix[i][j-1] - matrix[i-1][j-1];
}
}
set<int> data; data.insert(0);
for(int i = 0; i < matrix.size(); ++i) {
for(int j = 0; j < matrix[0].size(); ++j) {
if(data.count(target - matrix[i][j])) return true;
data.insert(matrix[i][j]);
}
}
return false;
}
One more variation:
Given an array of random integers, find subarray such that sum of elements in the element is divisible by K.
Suppse we have an array A[i] + A[i+1] + A[i+2].... =A[j] = target % k == 0
That is to say, (A[0] + A[1] + ... A[i-1]) % k = (A[0] + A[1] + A[2] .... A[j]) % k. We can use hash table to solve it as question 2.