Created
July 13, 2020 10:13
-
-
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
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 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