Lesson 51 of 73 2 min

Problem: 3Sum - Finding Unique Triplets

Learn how to find all unique triplets in an array that sum to zero using the Two Pointers pattern.

Problem Statement

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

The solution set must not contain duplicate triplets.

Approach: Sorting + Two Pointers

We can reduce the 3Sum problem to a "Two Sum" problem by fixing one number and searching for the other two.

  1. Sort the array: This allows us to use two pointers and easily skip duplicates.
  2. Iterate: Fix nums[i] and look for a pair in nums[i+1...n-1] that sums to -nums[i].
  3. Skip Duplicates: To avoid duplicate triplets, skip the current i if nums[i] == nums[i-1]. Also, skip duplicates when moving the two pointers.

Java Implementation

public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> res = new ArrayList<>();
    
    for (int i = 0; i < nums.length - 2; i++) {
        // Skip duplicate fixed element
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        
        int left = i + 1;
        int right = nums.length - 1;
        int target = -nums[i];
        
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) {
                res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                // Skip duplicates for left and right
                while (left < right && nums[left] == nums[left + 1]) left++;
                while (left < right && nums[right] == nums[right - 1]) right--;
                left++;
                right--;
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return res;
}

Complexity Discussion

  • Time Complexity: $O(n^2)$. Sorting takes $O(n \log n)$, and the nested loops take $O(n^2)$.
  • Space Complexity: $O(\log n)$ to $O(n)$ depending on the sorting implementation.

Interview Tips

  • Why sort? "Sorting helps in two ways: it enables the two-pointer approach and makes it easy to identify and skip duplicate elements."
  • Edge cases: Array length less than 3, all zeros, no valid triplets.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.