Skip to content

Instantly share code, notes, and snippets.

@deemaxx
Last active April 25, 2020 16:33
Show Gist options
  • Save deemaxx/645d7b34d64dd2d49323353628337c8b to your computer and use it in GitHub Desktop.
Save deemaxx/645d7b34d64dd2d49323353628337c8b to your computer and use it in GitHub Desktop.
Algorythms
// Given an array of numbers as an argument, and a number as a second argument
// find two numbers in the array that adds up the sum.
// const array = [2, 8, -19, 33, 923];
// const sum = 904;
// returns [-19, 923]
/**
* Function that searches for a pair of numbers which add up to the given sum
* @param array | Array<number>
* @param sum | number
* @returns Array<number>
*/
const numPairEqualSum = (array, sum) => {
// create a lookup set to store numbers of the array while looping over the array that may add up to the sum
// as the subsequent number is evaluated in the loop
let set = new Set();
// let's loop over the array and check if we have seen the complementary number we stored in the set
for (let i = 0; i < array.length; i++) {
if (set.has(sum - array[i])) {
return [(sum - array[i]), array[i]];
}
// if the number at the current index is not adding up to a number in the set we'll add it to the set
set.add(array[i]);
}
// if not two numbers add up to the sum, then return an empty array.
return [];
}
// time complexity: O(n)
// space complexity: O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment