Skip to content

Instantly share code, notes, and snippets.

@jerolan
Last active August 6, 2019 20:28
Show Gist options
  • Select an option

  • Save jerolan/fd552457d5224078c876b08b052bc583 to your computer and use it in GitHub Desktop.

Select an option

Save jerolan/fd552457d5224078c876b08b052bc583 to your computer and use it in GitHub Desktop.
/**
* TwoSum
* Write a function that takes a list and outputs alist of numbers
* belonging to the list that can be summed up to the first element of the list.
*
* Test Cases
* > twoSum [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]
* 6, 11, 10, 7, 15, 2
*
* > twoSum [7, 6, 4, 1, 7, -2, 3, 12]
* 6, 1, 4, 3
*/
function twoSum(array) {
const set = new Set(array);
const one = array[0];
return array.filter(two => set.has(one - two));
}
@codeams
Copy link

codeams commented Aug 6, 2019

Loved your approach.

A solution using only very common pieces of the language:

const twoSum = array => {
    const target = array[0]
    let awaitingFor = {}
    let results = []

    for (const number of array) {
        if (awaitingFor[number]) results.push([awaitingFor[number], number])
        else awaitingFor[target - number] = number
    }
    
    return results
}

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