Last active
December 9, 2017 07:22
-
-
Save sharmaabhinav/21f948e1fd312d4ea4641860e7fae332 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* given an array and value as k find if there is a subarray with sum = k */ | |
function findSubArray (arr, k) { | |
var sumArr = [] | |
var sum = 0 | |
for(var i=0;i<arr.length;i++) { | |
sum += arr[i] | |
if (sum === k) { | |
return [0, i] | |
} | |
sumArr.push(sum) | |
} | |
var map = {} | |
for(i=0;i<sumArr.length;i++) { | |
if (typeof map[sumArr[i] -k] !== 'undefined') { | |
return [map[sumArr[i] - k ] + 1, i] | |
} | |
map[sumArr[i]] = i | |
} | |
return -1 | |
} | |
console.log(findSubArray([1, 4, 3], 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment