Find the triplet that sum to a given value

Pattern: Two pointers

medium

Decide whether any three values add up to x, by sorting, fixing one value and searching the rest with two pointers.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers and a value x. Return true if some three values at three different positions add up to x, and false otherwise. For example, [1, 4, 45, 6, 10, 8] with x = 13 is true (1 + 4 + 8).

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name find3Numbers is this guide's own. The function may reorder the array.

Think first

  • How does this differ from 3Sum? Do you need all triplets, or just one?
  • After fixing one value, what is left to find?
  • Why does sorting make the remaining search fast?

Hints

    Brute force, and why it fails

    Check every triple with three nested loops: O(n³). Two loops plus a hash set for the third value is O(n²) with extra memory. Sorting and two pointers is O(n²) with no extra memory.

    The key insight

    Fixing one value reduces the question to "is there a pair with this sum in a sorted range?", which two pointers answer in one pass.

    Dry run

    10i
    41left
    62 
    83 
    104 
    455right
    sum50

    arr = [1, 4, 45, 6, 10, 8] and x = 13, sorted to [1, 4, 6, 8, 10, 45]. Fix i = 0 (value 1). The other two must sum to 12.

    Step 1 of 3

    The plan

    sort arr
    for i from 0 to n - 3:
        left = i + 1, right = n - 1
        while left < right:
            sum = arr[i] + arr[left] + arr[right]
            if sum == x: return true
            else if sum < x: left = left + 1
            else: right = right - 1
    return false
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    Sorting plus n pair searches of O(n) each. Only indexes are stored, besides the sort's own memory.

    Edge cases

    • Fewer than three values: false.
    • Repeated values, as in [1, 1, 1] with x = 3: true, because they sit at different positions.
    • Negative values work the same way.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean find3Numbers(int[] arr, int x) {
            Arrays.sort(arr);
            int n = arr.length;
            for (int i = 0; i < n - 2; i++) {
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    int sum = arr[i] + arr[left] + arr[right];
                    if (sum == x) {
                        return true;
                    } else if (sum < x) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool find3Numbers(vector<int>& arr, int x) {
            sort(arr.begin(), arr.end());
            int n = static_cast<int>(arr.size());
            for (int i = 0; i < n - 2; i++) {
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    int sum = arr[i] + arr[left] + arr[right];
                    if (sum == x) {
                        return true;
                    } else if (sum < x) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
            return false;
        }
    };

    Python

    class Solution:
        def find3Numbers(self, arr, x):
            arr.sort()
            n = len(arr)
            for i in range(n - 2):
                left, right = i + 1, n - 1
                while left < right:
                    total = arr[i] + arr[left] + arr[right]
                    if total == x:
                        return True
                    elif total < x:
                        left += 1
                    else:
                        right -= 1
            return False

    Common mistakes

    • Letting left or right reach i, which uses the same element twice.
    • Forgetting to sort first.
    • Continuing the search after finding a match.

    Similar problems