3Sum

Pattern: Two pointers

medium

Sort, fix the first value, and find the other two with pointers from both ends. Skip repeated values so every triplet is reported once.

The problem

You are given an array nums. Return every distinct triplet of values from three different positions that adds up to 0. A triplet may not appear twice in the answer. For example, [-1, 0, 1, 2, -1, -4] gives [-1, -1, 2] and [-1, 0, 1].

The function name threeSum matches LeetCode. Use the link above for the exact statement. LeetCode accepts the triplets in any order; this guide lists each triplet in increasing order and the triplets in sorted order.

Think first

  • Trying every triple is O(n³). If the first value is fixed, what problem is left?
  • After sorting, how do two pointers find a pair with a given sum?
  • [-1, -1, 0, 1] has two -1s. How do you avoid reporting [-1, 0, 1] twice?

Hints

    Brute force, and why it fails

    Three nested loops over all triples, with a set to remove repeated triplets: O(n³). For 3,000 numbers that is about 4.5 × 10⁹ triples, far too slow.

    The key insight

    Fixing one value turns 3Sum into a pair-sum problem on a sorted range, which two pointers solve in O(n). Doing that for each of the n fixed values gives O(n²), and sorting makes duplicates easy to skip.

    Dry run

    -40i
    -11left
    -12 
    03 
    14 
    25right
    fixed-4

    nums = [-1, 0, 1, 2, -1, -4], sorted to [-4, -1, -1, 0, 1, 2]. Fix i = 0 (value -4). The pair must sum to 4, but the biggest pair is 1 + 2 = 3, so left walks right without a match.

    Step 1 of 5

    The plan

    sort nums
    for i from 0 to n - 3:
        if i > 0 and nums[i] == nums[i - 1]: continue      # same first value
        left = i + 1, right = n - 1
        while left < right:
            sum = nums[i] + nums[left] + nums[right]
            if sum < 0: left = left + 1
            else if sum > 0: right = right - 1
            else:
                record [nums[i], nums[left], nums[right]]
                left = left + 1; right = right - 1
                while left < right and nums[left] == nums[left - 1]:
                    left = left + 1                         # same middle value
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    Sorting is O(n log n), and the n pair searches are O(n) each. Apart from the output and the sort's own memory, only a few indexes are used.

    Edge cases

    • [0, 0, 0] and [0, 0, 0, 0]: [[0, 0, 0]] once.
    • No triplet, as in [0, 1, 1]: an empty list.
    • Many repeated values: the skips keep the output free of repeats.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<>();
            int n = nums.length;
            for (int i = 0; i < n - 2; i++) {
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;                               // same first value as before: same triplets
                }
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    int sum = nums[i] + nums[left] + nums[right];
                    if (sum < 0) {
                        left++;                             // need a bigger sum
                    } else if (sum > 0) {
                        right--;                            // need a smaller sum
                    } else {
                        result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;                         // skip repeats of the middle value
                        }
                    }
                }
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            vector<vector<int>> result;
            int n = static_cast<int>(nums.size());
            for (int i = 0; i < n - 2; i++) {
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;                               // same first value as before: same triplets
                }
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    int sum = nums[i] + nums[left] + nums[right];
                    if (sum < 0) {
                        left++;                             // need a bigger sum
                    } else if (sum > 0) {
                        right--;                            // need a smaller sum
                    } else {
                        result.push_back({nums[i], nums[left], nums[right]});
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;                         // skip repeats of the middle value
                        }
                    }
                }
            }
            return result;
        }
    };

    Python

    class Solution:
        def threeSum(self, nums: list[int]) -> list[list[int]]:
            nums.sort()
            result = []
            n = len(nums)
            for i in range(n - 2):
                if i > 0 and nums[i] == nums[i - 1]:
                    continue                                # same first value as before: same triplets
                left, right = i + 1, n - 1
                while left < right:
                    total = nums[i] + nums[left] + nums[right]
                    if total < 0:
                        left += 1                           # need a bigger sum
                    elif total > 0:
                        right -= 1                          # need a smaller sum
                    else:
                        result.append([nums[i], nums[left], nums[right]])
                        left += 1
                        right -= 1
                        while left < right and nums[left] == nums[left - 1]:
                            left += 1                       # skip repeats of the middle value
            return result

    Common mistakes

    • Not skipping repeated first values, which reports the same triplet several times.
    • Skipping repeats before recording the first match, which can miss triplets like [-1, -1, 2].
    • Using a set of triplets on top of an O(n³) loop, which fixes repeats but not speed.

    Similar problems