Last active
April 10, 2020 21:39
-
-
Save d-beloved/77f02f17e74440edbe71592b57330585 to your computer and use it in GitHub Desktop.
Two Number Sum algorithm (Solution using two methods)
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
// 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) |
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
// 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) |
Author
d-beloved
commented
Feb 23, 2020
- 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