Tuesday, March 15, 2022

Three Number Sum

Given an array of distinct integers and a targetSum, find any three numbers that when added together equal to targetSum. Return them in ascending order. If there are more than one triplets, return them all. There will always be at least one.


function threeSum(array, targetSum) {
  array.sort((a, b) => a - b);
  const triplets = [];
  for (let i = 0; i < array.length - 2; i++) {
    let left = i + 1;
    let right = array.length - 1;
    while (left < right) {
      const currentSum = array[i] + array[left] + array[right];
      if (currentSum === targetSum) {
        triplets.push([array[i], array[left], array[right]]);
        left++;
        right--;
      } else if (currentSum < targetSum) {
        left++;
      } else {
        right--;
      }
    }
  }
 
  return triplets;
}

// 1, 2, 7
// 2, 3, 5
threeSum([7, 1, 5, 2, 3], 10);
// 1, 2, 6
// 1, 3, 5
// 2, 3, 4
threeSum([1, 2, 3, 4, 5, 6, 7], 9);

No comments:

Post a Comment

JWT Tokens

JWT tokens were created as a way to safely transfer small pieces of data as a JSON object. It's intended to be used to authenticate HTTP...