3Sum
The problem
Section titled “The problem”You get an array of integers. Return every set of three numbers (from three different positions) whose sum is 0. The result must not contain the same triplet twice, and the order of triplets or of numbers inside one doesn’t matter.
nums = [-1, 0, 1, 2, -1, -4] -> [[-1, -1, 2], [-1, 0, 1]]Key insight
Section titled “Key insight”Brute force checks all triplets: O(n³). Fixing one number turns the rest into Two Sum:
find two numbers that add to -nums[i].
Sort the array first. Then for each i, put one pointer just after i and one at the
end. If the three-number sum is too small, move left up. If it is too big, move right
down. If it is zero, record it and move both. Sorting also puts equal numbers side by
side, so duplicates are easy to skip: ignore an i equal to the previous i, and after
a hit, skip repeated values for left.
Show solutionHide solution
def three_sum(nums: list[int]) -> list[list[int]]: nums = sorted(nums) result = [] for i in range(len(nums) - 2): if nums[i] > 0: break # smallest is positive, so no triplet can sum to 0 if i > 0 and nums[i] == nums[i - 1]: continue # same first number as last time left, right = i + 1, len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total < 0: left += 1 elif total > 0: right -= 1 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 duplicate second numbers return resultexport function threeSum(nums: number[]): number[][] { const sorted = [...nums].sort((a, b) => a - b); const result: number[][] = []; for (let i = 0; i < sorted.length - 2; i++) { if (sorted[i] > 0) break; // smallest is positive, so no triplet can sum to 0 if (i > 0 && sorted[i] === sorted[i - 1]) continue; // same first number as last time let left = i + 1; let right = sorted.length - 1; while (left < right) { const total = sorted[i] + sorted[left] + sorted[right]; if (total < 0) left++; else if (total > 0) right--; else { result.push([sorted[i], sorted[left], sorted[right]]); left++; right--; while (left < right && sorted[left] === sorted[left - 1]) left++; // skip duplicate second numbers } } } return result;}import java.util.ArrayList;import java.util.Arrays;import java.util.List;
class Solution { public List<List<Integer>> threeSum(int[] nums) { int[] sorted = nums.clone(); Arrays.sort(sorted); List<List<Integer>> result = new ArrayList<>(); for (int i = 0; i < sorted.length - 2; i++) { if (sorted[i] > 0) break; // smallest is positive, so no triplet can sum to 0 if (i > 0 && sorted[i] == sorted[i - 1]) continue; // same first number as last time int left = i + 1, right = sorted.length - 1; while (left < right) { int total = sorted[i] + sorted[left] + sorted[right]; if (total < 0) { left++; } else if (total > 0) { right--; } else { result.add(Arrays.asList(sorted[i], sorted[left], sorted[right])); left++; right--; while (left < right && sorted[left] == sorted[left - 1]) left++; // skip duplicate second numbers } } } return result; }}Complexity
Section titled “Complexity”- Time: O(n²) — sorting is O(n log n); then each of n choices of
iruns a linear two-pointer scan. - Space: O(n) — the sorted copy (the output list is not counted). Sorting the input in place would leave only the sort’s own stack space, usually O(log n); say so if asked.
Watch out for
Section titled “Watch out for”- Duplicates are the hard part. Skip repeated
ivalues, and after recording a triplet skip repeatedleftvalues. Skippingrighttoo is optional: onceleftmoves to a new value, the sum changes and therightduplicates get passed naturally. - Compare against the previous
i, not the next one.nums[i] == nums[i - 1]keeps the first occurrence, so[-1, -1, 2]is still found. - Don’t use a set of triplets as a shortcut. It works but costs extra memory and hides that you understand the sorted skip.
- Early exit. Once
nums[i] > 0no later triplet can sum to zero.
Variations
Section titled “Variations”3Sum Closest (LeetCode 16)
Section titled “3Sum Closest (LeetCode 16)”Return the sum of three numbers closest to a target. The trick: same sort and fixed
i with two pointers, but track the sum with the smallest distance to the target
instead of collecting exact hits. Return immediately on an exact match.
4Sum (LeetCode 18)
Section titled “4Sum (LeetCode 18)”Find unique quadruplets that sum to a target. The trick: sort, add one more outer loop, then run the two-pointer scan inside. Skip duplicates at both outer loops. O(n³).
Two Sum II - Input Array Is Sorted (LeetCode 167)
Section titled “Two Sum II - Input Array Is Sorted (LeetCode 167)”The one-level version: a single pair in a sorted array. The trick: the inner two-pointer loop used here, with no outer loop and no duplicates to skip.