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 ] ];

Algorithm Overview

This problem is known as the "3Sum" problem. The algorithm uses a two-pointer technique:

  1. Sort the array to enable the two-pointer approach
  2. Fix one element and find two other elements that sum to the target
  3. Use left and right pointers to avoid nested loops
  4. Skip duplicates to prevent duplicate triplets

Example

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--;
                    left++;
                    right--;
                } else if(curr < sum) {
                    left++;
                } else if(curr > sum){
                    right--;
                }
            }
        }
    }
    return res;
};

console.log(threeSum(arr, sum));

Output

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

How It Works

The algorithm works by:

  • Sorting: Array is sorted to [1, 2, 5, 6, 7, 8, 9, 11]
  • Fixed element: For each element at index i, we look for pairs in the remaining array
  • Two pointers: Left starts after i, right starts at the end
  • Sum comparison: If sum is too small, move left pointer right; if too large, move right pointer left
  • Duplicate handling: Skip duplicate values to avoid duplicate triplets

Time Complexity

The time complexity is O(n²) where n is the array length. Sorting takes O(n log n), and the nested loop with two pointers takes O(n²).

Conclusion

This two-pointer approach efficiently finds all unique triplets that sum to a target value. The key is sorting the array first and using pointers to avoid duplicate combinations.

Updated on: 2026-03-15T23:19:00+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements