3Sum

MediumTwo Pointers · Sort + Fix One🧩 Two PointersLeetCode #15 ↗Updated

Problem

Given an integer array nums, list every distinct triplet of values [a, b, c], taken from three different positions, with a + b + c = 0. Two triplets with the same values (in any order) count once. The output order does not matter.
Input[-1,0,1,2,-1,-4]Output[[-1,-1,2],[-1,0,1]]
Input[0,1,1]Output[]
Input[0,0,0]Output[[0,0,0]]

3 ≤ n ≤ 3000  ·  -105 ≤ nums[i] ≤ 105  ·  no duplicate triplets

Try it yourself

Java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Sort, then fix the first value nums[i]: the rest is Two Sum II on the sorted suffix with target -nums[i]. Sorting also makes duplicates adjacent, so they are skipped with simple neighbour checks.
PatternTwo Pointers

Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.

Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.

Open the Two Pointers guide →

Approaches

Brute ForceAll Triplets + Set of Sorted Triplets

Time O(n3)Space O(n2)

Check every index triple i < j < k. To drop duplicates, sort each matching triplet and store it in a HashSet (at most O(n2) distinct triplets exist, since two values fix the third).

Java
public List<List<Integer>> threeSum(int[] nums) {
    Set<List<Integer>> triplets = new HashSet<>();
    int n = nums.length;
    for (int i = 0; i < n - 2; i++)
        for (int j = i + 1; j < n - 1; j++)
            for (int k = j + 1; k < n; k++)
                if (nums[i] + nums[j] + nums[k] == 0) {
                    List<Integer> t = Arrays.asList(nums[i], nums[j], nums[k]);
                    Collections.sort(t);
                    triplets.add(t);
                }
    return new ArrayList<>(triplets);
}

Correct but cubic: ~4.5·109 checks at n = 3000.

At a glance

LevelApproachTimeSpace
Brute ForceAll Triplets + Set of Sorted TripletsO(n3)O(n2)
BetterSort + HashSet Two Sum per iO(n2)O(n)
OptimalSort + Two PointersO(n2)O(log n)
Common pitfalls
  • Forgetting to skip duplicate nums[i] — emits [-1,0,1] twice.
  • Skipping duplicates before recording a hit loses [-1,-1,2].
  • Missing left < right in the skip loops — index out of bounds.
Interview tips
  • Say it out loud: “3Sum = sort + loop + Two Sum II”.
  • O(n2) is the accepted bound; sorting's O(n log n) is dominated.
  • Generalise: kSum recurses down to the same two-pointer core.
Pattern
Sort + fix one + two pointers → k-sum style problems that need unique combinations.
My notes saved in this browser