Find Triplet That Sums to a Given Value in JavaScript



In this article, we will learn to find three numbers in an array that add up to a given sum value using JavaScript. We are going to write a JavaScript program to find a triplet that sums up a given value. This program will make use of nested loops to iterate over the input array and check for the existence of a triplet with a sum equal to the given value. We'll present two different approaches and analyze their implementations.

Sorting and Two-Pointer Technique

The first approach uses sorting and the two-pointer technique to solve the problem efficiently. This method ensures that we can find all possible triplets in a well-organized manner, significantly reducing unnecessary comparisons.

following the steps for finding a triplet that sums up to a given value using the two-pointer technique ?

  • Sort the input array in ascending order.

  • Loop through the array and fix one element

  • Initialize two pointers, one pointing to the next element of the fixed element, and the other pointing to the end of the array.

  • Check if the sum of the three elements is equal to the given value.

  • If the sum is less than the given value, increment the left pointer.

  • If the sum is greater than the given value, decrement the right pointer. Repeat the process until either a triplet is found or the pointers cross each other.

Sorting the array in ascending order using the sort() method ?

arr.sort((a, b) => a - b);

Example

Below is an example of finding a triplet that sums up to a given value using the two-pointer technique ?

function findTriplet(arr, sum) {
   
   // First, we sort the array in ascending order
   arr.sort((a, b) => a - b);
     
   // Next, we iterate through the array with the outer loop
   for (let i = 0; i < arr.length - 2; i++) {
      
      // We start the inner loop from i + 1 to avoid using the same number twice
      let left = i + 1;
      let right = arr.length - 1;
         
      // The inner loop moves the left and right pointers towards each other
      while (left < right) {
         
         // If the sum of the current triplet is equal to the given sum, we have found our  solution
         if (arr[i] + arr[left] + arr[right] === sum) {
            return [arr[i], arr[left], arr[right]];
         }
         
         // If the sum of the current triplet is less than the given sum, we need to increase the sum
         
         // So, we move the left pointer to the right
         else if (arr[i] + arr[left] + arr[right] < sum) {
            left++;
         }
         
         // If the sum of the current triplet is greater than the given sum, we need to decrease the sum
         
         // So, we move the right pointer to the left
         else {
            right--;
         }
      }
   }
    
   // If no triplet is found, we return null
   return null;
}

// Example usage
let arr = [1, 4, 45, 6, 10, 8];
let sum = 22;
let triplet = findTriplet(arr, sum);
console.log(triplet); 

Output

[4, 8, 10]

Time Complexity: O(n^2) the two-pointer loop runs O(n^2) in the worst case.
Space Complexity: O(1) only constant extra space is used for pointers and variables.

Using a Map to Store Indices

The second approach uses the Map object to store the indices of elements and their values. This method is particularly useful when you need to find multiple triplets or handle large datasets more efficiently.

Create an empty object to store index-value pairs ?

const map = new Map();
const tripletSet = new Set();

Iterate through the array and populate the map using the map.set() ?

for (let i = 0; i < arr.length; i++) {
        map.set(i, arr[i]);
    }

Example

Below is an example of finding a triplet that sums to a given value using the map object ?

function findTriplet(arr, sum) {
    // Create an empty object to store index-value pairs
    const map = new Map();
    const tripletSet = new Set();

    // Iterate through the array and populate the map
    for (let i = 0; i < arr.length; i++) {
        map.set(i, arr[i]);
    }

    // Iterate through the array again to find triplets
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            const currentSum = arr[i] + arr[j];
            const requiredValue = sum - currentSum;

            // Check if the required value exists in the map
            if (map.has(requiredValue) && map.get(requiredValue) !== i && map.get(requiredValue) !== j) {
                tripletSet.add([arr[i], arr[j], requiredValue]);
            }
        }
    }

    // Convert the set to an array and return one of the triplets found, or null if none
    const triplets = Array.from(tripletSet);
    return triplets.length > 0 ? triplets[0] : null;
}
// Example usage
let arr = [1, 4, 45, 6, 10, 8];
let sum = 22;
let triplet = findTriplet(arr, sum);
console.log(triplet); 

Output

[10, 8, 4]

Time Complexity: O(n^2), Iterating through the array with nested loops takes O(n^2), and map operations are O(1) on average.
Space Complexity: O(n) the map requires additional space to store up to n elements from the array.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-27T19:17:21+05:30

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements