Skip to content

Instantly share code, notes, and snippets.

@r-i-c-h
Created October 21, 2019 20:02
Show Gist options
  • Save r-i-c-h/b5378bf3bc70ba31ae95002f0c4387ad to your computer and use it in GitHub Desktop.
Save r-i-c-h/b5378bf3bc70ba31ae95002f0c4387ad to your computer and use it in GitHub Desktop.
JS SubsetSum
// 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]
@r-i-c-h
Copy link
Author

r-i-c-h commented Oct 21, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment