Skip to content

Instantly share code, notes, and snippets.

@akaila
Last active October 14, 2015 16:15
Show Gist options
  • Save akaila/552f88ae95593883db10 to your computer and use it in GitHub Desktop.
Save akaila/552f88ae95593883db10 to your computer and use it in GitHub Desktop.
Given an array of positive integers and a target integer, find if there is a consecutive subarray that sums to the target. E.g, given {5,6,4,12}, findsum(10)=true, findsum(11)=false.
/*
Given an array of positive integers and a target integer, find if there is a consecutive subarray that sums to the target.
E.g, given {5,6,4,12}, findsum(10)=true, findsum(11)=false.
http://www.glassdoor.com/Interview/Given-an-array-of-positive-integers-and-a-target-integer-find-if-there-is-a-consecutive-subarray-that-sums-to-the-target-QTN_984284.htm
*/
function findSubarraySum(numbers, sum) {
var sumSoFar = 0;
var start = 0;
var end = 0;
while (start < numbers.length) {
if (sumSoFar == sum) {
return true;
} else if (sumSoFar > sum) {
sumSoFar -= numbers[start];
start++;
} else if (end < numbers.length) {
sumSoFar += numbers[end];
end++;
}
}
return (sumSoFar == sum);
}
console.log(findSubarraySum([5,6,4,12], 11));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment