JS - Educative-Twopointers-02

QUESTION: Sum of Three Values

  • Given an array of integers, nums, and an integer value, target, determine if there are any three integers in nums whose sum is equal to the target
  • Return true if three such integers exist in the array, otherwise return false.
  • The triplet are elements with disttinct indexes.
Explanation:
nums[i] + nums[j] + nums[k] == target;

SOLUTION:

Using 2-Pointers
const findSumOfThree = (s) => {
  // Sort the input array
  nums.sort((a, b) => a - b);
 
  const result = [];
 
  // Iterate through the array
  for (let i = 0; i < nums.length - 2; i++) {
    // Initialize two pointers
    let j = i + 1;
    let k = nums.length - 1;
 
    // While j is less than k
    while (j < k) {
      // Compute the sum of the three elements
      const sum = nums[i] + nums[j] + nums[k];
 
      if (sum === target) {
        // Add these three elements to the result array
        result.push([nums[i], nums[j], nums[k]]);
 
        // Move both pointers towards the center
        j++;
        k--;
      } else if (sum < target) {
        // Increment j if the sum is less than the target sum
        j++;
      } else {
        // Decrement k if the sum is greater than the target sum
        k--;
      }
    }
  }
 
  return result;
};
 
const nums = [-1, 0, 1, 2, -1, -4];
const target = 0;
const result = threeSum(nums, target);
console.log(result); // [ [ -1, -1, 2 ], [ -1, 0, 1 ], [ -1, 0, 1 ] ]

Time complexity

  • The time complexity is O(n) where n is the number of characters present in the string.

Space complexity

  • The space complexity is O(1) because we use constant space to store two indices.