Algo-Sim › Two Pointers

3Sum

Medium · Two Pointers · step through it in Java, Python and C++ on your own input

Find all unique triplets that sum to zero: sort, fix one number, then sweep a pair with two pointers.

Problem

Given an integer array nums, return every distinct triplet of values [a, b, c], taken from three different positions, with a + b + c = 0. Two triplets with the same values count once, and the order of the output does not matter.

Constraints

Edge cases to test

Follow-up questions

How are duplicate triplets avoided?
Skip equal values for the fixed number, and after a hit move both pointers past equal neighbours. No set of triplets needed.
What about 4Sum or k-Sum?
Fix numbers recursively down to a two-pointer 2Sum: O(n^(k−1)) time.
What about the closest sum to a target?
The same sort and sweep, tracking the smallest |sum − target| (LC 16): O(n²).

Solution

Java

public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> result = new ArrayList<>();
    for (int i = 0; i < nums.length - 2; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        int lo = i + 1, hi = nums.length - 1;
        while (lo < hi) {
            int sum = nums[i] + nums[lo] + nums[hi];
            if (sum < 0) {
                lo++;
            } else if (sum > 0) {
                hi--;
            } else {
                result.add(List.of(nums[i], nums[lo], nums[hi]));
                while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                lo++;
                hi--;
            }
        }
    }
    return result;
}

Python

def three_sum(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        lo, hi = i + 1, len(nums) - 1
        while lo < hi:
            total = nums[i] + nums[lo] + nums[hi]
            if total < 0:
                lo += 1
            elif total > 0:
                hi -= 1
            else:
                result.append([nums[i], nums[lo], nums[hi]])
                while lo < hi and nums[lo] == nums[lo + 1]:
                    lo += 1
                while lo < hi and nums[hi] == nums[hi - 1]:
                    hi -= 1
                lo += 1
                hi -= 1
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> threeSum(vector<int> &nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> result = {};
        for (int i = 0; i < int(nums.size()) - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int lo = i + 1, hi = int(nums.size()) - 1;
            while (lo < hi) {
                int sum = nums[i] + nums[lo] + nums[hi];
                if (sum < 0) {
                    lo++;
                } else if (sum > 0) {
                    hi--;
                } else {
                    result.push_back({nums[i], nums[lo], nums[hi]});
                    while (lo < hi && nums[lo] == nums[lo + 1])
                        lo++;
                    while (lo < hi && nums[hi] == nums[hi - 1])
                        hi--;
                    lo++;
                    hi--;
                }
            }
        }
        return result;
    }
};

More Two Pointers problems