Skip to content

Instantly share code, notes, and snippets.

@d-beloved
Last active April 10, 2020 21:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-beloved/77f02f17e74440edbe71592b57330585 to your computer and use it in GitHub Desktop.
Save d-beloved/77f02f17e74440edbe71592b57330585 to your computer and use it in GitHub Desktop.
Two Number Sum algorithm (Solution using two methods)
// Two Number sum algorithm challenge
// Solution using the algebraic method
const twoNumberSum = (array, targetSum) => {
const hashTable = {}
for (let value of array) {
let yValue = targetSum - value;
if (hashTable[yValue]) {
return [yValue, value]
}
else {
hashTable[value] = true
}
}
return []
}
let array = [-1, 4, 5, 9, 2, 19, 14, 57, 102, 73];
let targetSum = 87;
twoNumberSum(array, targetSum)
// sorting algorithm method
const twoNumberSum = (array, targetSum) => {
let sortedArray = array.sort((a, b) => a - b);
let countFwd = 0;
let countBwd = 1;
let firstPointer = sortedArray[countFwd]
let lastPointer = sortedArray[sortedArray.length - countBwd]
for(let i = 0; i < sortedArray.length; i++) {
let sum = firstPointer + lastPointer;
if(targetSum > sum) {
firstPointer = sortedArray[countFwd++]
}
else if(targetSum < sum) {
lastPointer = sortedArray[sortedArray.length - countBwd++]
}
else{
return [firstPointer, lastPointer]
}
}
return []
}
let array = [-1, 4, 5, 9, 2, 19, 14, 57, 102, 73];
let targetSum = 87;
twoNumberSum(array, targetSum)
@d-beloved
Copy link
Author

  • The blog for this gist is available here

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