Created
October 21, 2019 20:02
-
-
Save r-i-c-h/b5378bf3bc70ba31ae95002f0c4387ad to your computer and use it in GitHub Desktop.
JS SubsetSum
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
// Will actually work without the 'String()` whatnot, but I'm being particular | |
const subsetSum = (arr, target) => { | |
let dictObj = {}; | |
for (let i = 0; i < arr.length; i++) { | |
const val = arr[i]; | |
const compliment = String(target - val); | |
if (dictObj.hasOwnProperty(compliment)) { // must use hasOwnProp in case of index=0 which would return as false!! | |
return [dictObj[compliment],i]; | |
} | |
dictObj[String(val)] = i; | |
} | |
return false; | |
}; | |
console.log(subsetSum([2, 7, 11, 6], 9)); // [0,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sacrifices O(n^2) to become 0(n), but adds the space complexity of O(n) which doesn't happen in an embedded-loop version.