Skip to content

Instantly share code, notes, and snippets.

@jensendarren
Created July 13, 2020 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jensendarren/ff7d37bf0a5d770dc0d800280f7584b5 to your computer and use it in GitHub Desktop.
Save jensendarren/ff7d37bf0a5d770dc0d800280f7584b5 to your computer and use it in GitHub Desktop.
Given a list of numbers an a number k, return whether any two number from the list add up to k
/*
Given a list of numbers an a number k, return whether any two number from the list add up to k
For example. given [10,15,3,7] and k of 17 return true sine 10 + 7 is 17.
Bonus can you do in a single pass?
*/
array = [7,15,3,7,8,3,4,100]
k = 23
// e1 + e2 = k
// e2 = k - e1
verifySol = (_array, _k) => {
hashMap = {};
for(let e of _array) {
if (hashMap[e]) {
return true;
} else {
// Store the value that we are looking for
// which is: e2 = k - e1
hashMap[k-e] = true
}
}
return false;
}
console.log(`Given the list ${array} and a desired sum ${k}: `)
console.log()
let res = verifySol(array, k);
console.log("Result using solution 1 (single pass hash map)", res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment