Skip to content

Instantly share code, notes, and snippets.

@joeydotdev
Created December 31, 2019 15:04
Show Gist options
  • Save joeydotdev/c54e6c513a790c679dc1c709c7f4d48d to your computer and use it in GitHub Desktop.
Save joeydotdev/c54e6c513a790c679dc1c709c7f4d48d to your computer and use it in GitHub Desktop.
const twoSum = (arr, target) => {
const hashTable = {};
populateTable(hashTable, arr);
for (let i = 0; i < arr.length; i++) {
const desiredValue = target - arr[i];
if (validValueExists(desiredValue, hashTable, i)) {
return [i, hashTable[desiredValue]];
}
}
return [-1, -1];
};
const validValueExists = (desiredValue, hashTable, currentIndex) => {
return (
// Make sure there exists a key with `desiredValue`.
hashTable.hasOwnProperty(desiredValue)
// Make sure we aren't re-using the same index.
&& hashTable[desiredValue] !== currentIndex
);
}
const populateTable = (hashTable, arr) => {
for (let i = 0; i < arr.length; i++) {
hashTable[arr[i]] = i;
}
}
console.log(twoSum([2, 1, 4, 3], 6)); // [0, 2]
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment