Created
August 29, 2019 16:35
-
-
Save ealipio/c9f37adcb70e2ee23bc0a71bc7f919bd to your computer and use it in GitHub Desktop.
This file contains 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
// Write an algorithm to check if the sum of any two elements in an | |
// array/list matches a given target, and return their indexes in | |
// an array. | |
// | |
// Parameters: [0, 6, 8, 4], 10 | |
// Result: [ 1, 3] | |
// Parameters: [20, 18, 5, 4, 10, 22], 42 | |
// Result: [ 0, 5] | |
const sumContainsTarget = (arr = [] , target ) => { | |
const params = {}; | |
for(let i = 0; i< arr.length; i++) { | |
params[arr[i]] = i | |
} | |
for( let i = 0; i < arr.length; i++) { | |
const nextNumber = target - arr[i]; | |
if(params[nextNumber]) { | |
return [i, params[nextNumber]] | |
} | |
} | |
return []; | |
} | |
const result = sumContainsTarget([0, 6, 8, 4], 10); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment