Guide contents

Lesson 25 of 250

15. 3Sum

NeetCode: 3Sum · LeetCode: 15. 3Sum · Difficulty: Medium

Return all unique triplets [a, b, c] from nums (using distinct indices) such that a + b + c == 0. The result must not contain duplicate triplets; order does not matter.

Example

Text
Input:  nums = [-1, 0, 1, 2, -1, -4]    Output: [[-1, -1, 2], [-1, 0, 1]]

Brute force: three loops and a set

Try every triple of indices, sort each triplet's values, and store it in a HashSet<List<Integer>> to remove duplicates. A List is used because it compares by contents, while an int[] in a set would compare by identity. The final list is sorted so the output is deterministic.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> found = new HashSet<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if (nums[i] + nums[j] + nums[k] == 0) {
                        int[] t = {nums[i], nums[j], nums[k]};
                        Arrays.sort(t);
                        found.add(Arrays.asList(t[0], t[1], t[2]));
                    }
                }
            }
        }
        List<List<Integer>> result = new ArrayList<>(found);
        result.sort((a, b) -> {
            for (int i = 0; i < 3; i++) {
                int c = Integer.compare(a.get(i), b.get(i));
                if (c != 0) {
                    return c;
                }
            }
            return 0;
        });
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
        System.out.println(s.threeSum(new int[]{0, 0, 0}));
        System.out.println(s.threeSum(new int[]{0, 1, 1}));
    }
}
Output
[[-1, -1, 2], [-1, 0, 1]]
[[0, 0, 0]]
[]

Time: O(n³). Space: O(n) for the set.

The sum of three int values wraps silently on overflow, so values near Integer.MAX_VALUE or Integer.MIN_VALUE need long sums. The examples here are small.

Optimal: sort, fix one number, two pointers for the rest

Sort the array (Arrays.sort sorts nums in place, which is allowed here). For each nums[i], the other two numbers must sum to -nums[i], which is a Two Sum II on the part to the right of i. Duplicates are skipped explicitly: skip an i equal to the previous one, and after finding a triplet, move left past equal values.

Because the array is sorted, once nums[i] > 0 no three numbers from i onward can sum to zero, so the loop can stop there. n - 1 is -1 for an empty array, so left < right fails at once and no guard is needed.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1, right = n - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum < 0) {
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                }
            }
        }
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
        System.out.println(s.threeSum(new int[]{0, 0, 0}));
        System.out.println(s.threeSum(new int[]{0, 1, 1}));
    }
}
Output
[[-1, -1, 2], [-1, 0, 1]]
[[0, 0, 0]]
[]

Time: O(n²): the sort is O(n log n), and each i costs a linear two-pointer scan. Space: O(1) beyond the sort and the output.