Two Sum Problem in javascript

Two Sum Problem in javascript

An array and a targetedSum are given and we need to find out if 2 elements are added are equal to the targetedSum

3 Ways we can solve the problem

1) Iteration - 2 for loops first loop from i(i.e 0 to array length) and second loop from i+1

2) Storing the elements(Which is currentElement - targetedSum) and checking if that element is present or there, If present we return true else false.

function twoSum(array, targetedSum) {
 // O(n) Time and O(1) Space
// to store the key as true
  let obj = {};

// loop the array
  for (let currentElement of array) {
    let ans = targetedSum - currentElement;

    if (obj[ans]) {
      return true;
    } else {
      obj[currentElement] = true;
    }
  }

  return false;
}


twoSum([3, 5, -4, 8, 11, 1, -1, 6], 10) // true

3) Two-pointer Technique - Sorting the elements in the array and with the help of 2 pointer technique we find out the solutions

function twoPointerSum(array, targetedSum) {
    // O(nlogn) Time and O(1) Space
    array.sort((a,b) => a-b)

    let left = 0
    let right = array.length - 1

    while(left < right) {
        if(array[left] + array[right] === targetedSum) {
             return true;
        } else if(array[left] + array[right] > targetedSum) {
            right--;
        } else {
            left++
        }
    }
    return false;

}

Thanks and keep visiting this blog :)