3-Sum (LeetCode 15)
3-Sum (LeetCode 15): 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
TRIPLETS SUMMING TO 0
SORT
0
1
2
3
4
5
Fixed
:
Sum
:
Found
0
result
No triplet yet
Sort: [-4, -1, -1, 0, 1, 2]. Equal values are now neighbours, which is what lets duplicates be skipped
Next
Fix nums[0] = -4: look for two values after it summing to 4
Array
Sorted before the scan, as the code does
The figure fixes i and moves the L and R pointers to find pairs summing to -nums[i]; recorded triplets collect beside it.
3-Sum Dry Run
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};
3-Sum in Python, Java, C++, TypeScript and C
3-Sum in Python
def threeSum(nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
n = len(nums)
for i in range(n - 2):
# Skip duplicates for i
if i > 0 and nums[i] == nums[i-1]:
continue
left = i + 1
right = n - 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]])
# Skip duplicates for left and right
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return result3-Sum in Java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left+1]) left++;
while (left < right && nums[right] == nums[right-1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
}3-Sum in C++
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int n = nums.size();
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int left = i + 1;
int right = n - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left+1]) left++;
while (left < right && nums[right] == nums[right-1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
};3-Sum in TypeScript
function threeSum(nums: number[]): number[][] {
nums.sort((a, b) => a - b);
const result: number[][] = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}3-Sum in C
int cmp(const void* a, const void* b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
qsort(nums, numsSize, sizeof(int), cmp);
int capacity = 16;
int** result = malloc(capacity * sizeof(int*));
*returnSize = 0;
for (int i = 0; i < numsSize - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = numsSize - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
if (*returnSize == capacity) {
capacity *= 2;
result = realloc(result, capacity * sizeof(int*));
}
result[*returnSize] = malloc(3 * sizeof(int));
result[*returnSize][0] = nums[i];
result[*returnSize][1] = nums[left];
result[*returnSize][2] = nums[right];
(*returnSize)++;
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
*returnColumnSizes = malloc(*returnSize * sizeof(int));
for (int t = 0; t < *returnSize; t++) (*returnColumnSizes)[t] = 3;
return result;
}More practice: DSA interview questions with answers · patterns cheat sheet
