Skip to content

Instantly share code, notes, and snippets.

@raphaeladrien
Last active October 16, 2021 22:03
Show Gist options
  • Save raphaeladrien/a807675006163c028dec32ee29f16126 to your computer and use it in GitHub Desktop.
Save raphaeladrien/a807675006163c028dec32ee29f16126 to your computer and use it in GitHub Desktop.
Two sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Solution:

var twoSum = function(nums, target) {
    const storage = new Map()
    let output = []
    
    nums.forEach(function(value, index) {
        const difference = target - value;
        if (storage.has(difference)){
            output = [storage.get(difference), index]
            return;
        }
        
        storage.set(value, index)
    })
    
    return output
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment