Pair of elements from a specified array whose sum equals a specific target number

that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming

In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.

Lets investigate how it works to better understand it:

twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler

In iteration 0:

value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.

So in our map, 40 points to 0.

In iteration 2:

value is 40. I look at map my map to see I previously found a pair for 40.

map[nums[x]] (which is the same as map[40]) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.


Does that make any sense now?

Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)

Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)


Using HashMap approach using time complexity approx O(n),below is the following code:

let twoSum = (array, sum) => {
    let hashMap = {},
      results = []

        for (let i = 0; i < array.length; i++){
            if (hashMap[array[i]]){
                results.push([hashMap[array[i]], array[i]])
            }else{
                hashMap[sum - array[i]] = array[i];
            }
          }
          return results;
    }
console.log(twoSum([10,20,10,40,50,60,70,30],50));

result:

{[10, 40],[20, 30]}

I think the code is self explanatory ,even if you want help to understand it,let me know.I will be happy enough to for its explanation.

Hope it helps..


Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)

((arr,targetSum) => {
    if ((arr && arr.length === 0) || targetSum === undefined) {
        return false;
    } else {
        for (let x = 0; x <=arr.length -1; x++) {
            let partnerInPair = targetSum - arr[x];
            let start = x+1;
            let end = (arr.length) - 2;

             while(start <= end) {
                let mid = parseInt(((start + end)/2));
                if (arr[mid] === partnerInPair) {
                    console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
                    break;
                } else if(partnerInPair < arr[mid]) {
                    end = mid - 1;
                } else if(partnerInPair > arr[mid]) {
                    start = mid + 1;
                }
             }
        };

    };
})([0,1,2,3,4,5,6,7,8,9], 10)