Finding three elements with required sum in an array in JavaScript


We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should then pick three such numbers from the array, (if they exist) whose sum is equal to the number specified by the second argument.

The function should finally return an array of arrays of all such triplets if they exist, an empty array otherwise.

For example −

If the input array and the number is −

const arr = [2, 5, 7, 8, 9, 11, 1, 6];
const sum = 22;

Then the output should be −

const output = [ [ 2, 9, 11 ], [ 5, 6, 11 ], [ 5, 8, 9 ], [ 6, 7, 9 ] ];

Example

The code for this will be −

const arr = [2, 5, 7, 8, 9, 11, 1, 6];
const sum = 22;
const threeSum = (arr = [], sum) => {
   arr.sort((a,b) => a - b);
   const res = [];
   for(let i=0; i < arr.length - 2; i++){
      if(arr[i] != arr[i-1]){
         let left = i + 1;
         let right = arr.length - 1;
         while (left < right){
            const curr = arr[i] + arr[left] + arr[right];
            if (curr === sum){
               res.push([arr[i], arr[left], arr[right]]);
               while(arr[left] == arr[left + 1]) left ++
               while(arr[right] == arr[right - 1]) right -- // making sure
               our solution set does not contain duplicate res
               left ++;
               right --;
            } else if(curr < sum) {
               left ++
            } else if(curr > sum){
               right --
            };
         };
      };
   };
   return res
};
console.log(threeSum(arr, sum));

Output

And the output in the console will be −

[ [ 2, 9, 11 ], [ 5, 6, 11 ], [ 5, 8, 9 ], [ 6, 7, 9 ] ]

Updated on: 24-Feb-2021

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements