Last active
January 14, 2019 18:30
-
-
Save mrharel/5a20e1eff1420e7ea7ab1f49d3901a48 to your computer and use it in GitHub Desktop.
Determine if any 3 integers in an array sum to 0. Note: The following solutions assumes that repetitions (i.e. choosing the same array element more than once) are allowed, so the array [-5,1,10] contains a zero sum (-5-5+10) and so does [0] (0+0+0). [4, 2, -1, 1, -5, 6, -4] = True
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
function detectZero(arr) { | |
const map = {}; | |
for (var i=0; i<arr.length; i++) { | |
if (arr[i] === 0) return true; | |
if (map[arr[i]]) return true; | |
map[arr[i] * -2] = true; | |
if (find2Sum(arr.slice(i), -arr[i])) return true; | |
} | |
return false; | |
} | |
function find2Sum(arr, sum) { | |
const map = {}; | |
for (var i=0; i<arr.length; i++) { | |
if (map[arr[i]]) return true; | |
map[sum - arr[i]] = true; | |
} | |
return false; | |
} | |
const arr1 = [-5,3,1,-8]; | |
console.log(detectZero(arr1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment