Skip to content

Instantly share code, notes, and snippets.

@ealipio
Created August 29, 2019 16:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ealipio/c9f37adcb70e2ee23bc0a71bc7f919bd to your computer and use it in GitHub Desktop.
// 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