3-Sum
Find every group of three values, taken from different positions in the integer array nums, that adds up to 0, listing each distinct triplet once.
Examples
Two different triplets reach 0: [-1,0,1] and [-1,-1,2]. They may come back in any order, and so may the numbers inside each one.
With exactly three numbers there is one triplet to try, and its sum is 2, not 0.
The only possible triplet sums to 0.
Problem Understanding
The goal is to find all unique triplets that sum to zero. It's essentially an extension of the Two Sum problem.
Key Constraint: The solution set must not contain duplicate triplets. This implies we need to be careful about how we select numbers.
Strategy: Reduce to Two Sum
We can fix one number, say nums[i]. Then the problem becomes finding two other numbers in the rest of the array that sum to -nums[i].
Since we want to avoid duplicates and use the Two Pointer technique efficiently, our first step is to sort the array.
Algorithm:
- Sort the array.
- Iterate through the array with index
i. - For each
i, run the Two Sum (Sorted) logic on the remaining part of the array (i+1to end) withtarget = -nums[i].
Interactive Visualization
The figure fixes i and moves the L and R pointers to find pairs summing to -nums[i]; recorded triplets collect beside it.
Dry Run Table
Input: nums = [-1, 0, 1, 2, -1, -4] -> Sorted: [-4, -1, -1, 0, 1, 2]
| i (val) | Left (val) | Right (val) | Sum | Action |
|---|---|---|---|---|
| 0 (-4) | 1 (-1) | 5 (2) | -3 | Too small. L++ |
| ... | ... | ... | ... | (No triplets for -4) |
| 1 (-1) | 2 (-1) | 5 (2) | 0 | Match! Record [-1,-1,2]. L++, R-- |
| 1 (-1) | 3 (0) | 4 (1) | 0 | Match! Record [-1,0,1]. L++, R-- |
| 2 (-1) | ... | ... | ... | Skip duplicate i! |
| 3 (0) | 4 (1) | 5 (2) | 3 | Too big. |
Result: [[-1,-1,2], [-1,0,1]]
Edge Cases & Common Mistakes
Edge Cases:
- Fewer than 3 elements: Impossible to find a triplet. Return empty.
- No Solution: Return empty list.
- All Zeros: Should return
[[0,0,0]].
Common Mistakes:
- Duplicate Triplets: The problem asks for unique triplets. You MUST skip duplicate values for both
iand the two pointersL,Rafter finding a match. - Not Sorting: The Two Pointer logic for 3-Sum relies heavily on the array being sorted.
Solution
3-Sum Code
1/**2 * @param {number[]} nums3 * @return {number[][]}4 */5var threeSum = function(nums) {6 nums.sort((a, b) => a - b);7 const result = [];89 for (let i = 0; i < nums.length - 2; i++) {10 if (i > 0 && nums[i] === nums[i - 1]) continue;1112 let left = i + 1;13 let right = nums.length - 1;1415 while (left < right) {16 const sum = nums[i] + nums[left] + nums[right];1718 if (sum === 0) {19 result.push([nums[i], nums[left], nums[right]]);20 while (left < right && nums[left] === nums[left + 1]) left++;21 while (left < right && nums[right] === nums[right - 1]) right--;22 left++;23 right--;24 } else if (sum < 0) {25 left++;26 } else {27 right--;28 }29 }30 }31 return result;32};
