3Sum
You are given an integer array nums. Find every distinct triplet of values [a, b, c] such that a + b + c == 0, where the three values come from three different positions in the array.
Two triplets count as the same if they contain the same values, so your answer must not list any group of three values twice, even when the array contains repeated numbers. A value may appear more than once inside one triplet only if it occurs that many times in nums.
Return the triplets in any order; the order of the numbers inside each triplet does not matter either. If no triplet sums to zero, return an empty list.
Example 1
Example 2
Example 3
Constraints
3 <= nums.length <= 3000-105 <= nums[i] <= 105
Pattern Path · Two Pointers · problem 19 of 169
a, what problem is left for the other two?-a. Which problem is that, and how does it get easier on a sorted array?i, move two pointers inward from both ends of the rest of the array, comparing the sum against zero.i whose value equals the previous one, and after recording a triplet move the left pointer past all copies of the same value.Start simple
Check all three-index combinations and deduplicate the found triplets with a set: O(n³) time.
The key idea
Sort the array first. Sorting does two jobs: it lets two pointers find pairs with a given sum, and it puts equal values next to each other so duplicates are easy to skip.
Pick each index i as the smallest value of the triplet. The remaining two values must sum to -nums[i] and lie to the right of i. Put lo just after i and hi at the end. If the three values sum to less than zero, the only way to increase the sum is to move lo right; if the sum is too big, move hi left. Each step discards a value that cannot belong to any remaining answer for this i, so the scan is linear.
Duplicates are handled by skipping, not by a set: ignore an i equal to the previous value (it would find the same triplets), and after a hit advance lo past repeats of the value just used. Once nums[i] > 0 you can stop, because three positive numbers never sum to zero.
Complexity
- Time:
O(n²) - Space:
O(1) extra besides the output (O(n) or O(log n) for sorting)
Python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n - 2):
if nums[i] > 0:
break # the smallest value is positive: no more zero sums
if i > 0 and nums[i] == nums[i - 1]:
continue # same first value would repeat the same triplets
lo, hi = i + 1, n - 1
while lo < hi:
total = nums[i] + nums[lo] + nums[hi]
if total < 0:
lo += 1
elif total > 0:
hi -= 1
else:
result.append([nums[i], nums[lo], nums[hi]])
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip copies of the value just used
return result
JavaScript
var threeSum = function(nums) {
nums.sort((a, b) => a - b);
const n = nums.length;
const result = [];
for (let i = 0; i < n - 2; i++) {
if (nums[i] > 0) break; // the smallest value is positive: no more zero sums
if (i > 0 && nums[i] === nums[i - 1]) continue; // same first value, same triplets
let lo = i + 1, hi = n - 1;
while (lo < hi) {
const total = nums[i] + nums[lo] + nums[hi];
if (total < 0) {
lo++;
} else if (total > 0) {
hi--;
} else {
result.push([nums[i], nums[lo], nums[hi]]);
lo++;
hi--;
while (lo < hi && nums[lo] === nums[lo - 1]) lo++; // skip copies
}
}
}
return result;
};
What the interviewer is checking
It checks whether you can reduce a new problem to one you know (Two Sum on a sorted array) and handle duplicates cleanly without falling back on a set of tuples.
Mistakes to avoid
- Deduplicating only the first value and still reporting the same pair for
loandhitwice. - Skipping duplicates of
nums[i]by comparing withnums[i + 1], which wrongly drops triplets like [-1, -1, 2]. - Forgetting to move both pointers after a match, which causes an infinite loop.
- Using a hash set of tuples on the brute force: correct but O(n³).
Follow-ups to expect
- How would you solve 4Sum or k-Sum? (Recurse down to two-pointer Two Sum.)
- What if you only need the triplet closest to a target? (Same scan, track best difference.)
- Can you do it without sorting? (Hash set per i, harder dedup.)
In real software
Finding small groups of transactions or ledger entries that cancel each other out to zero is the same search, and sort-plus-two-pointers is a common way to do it in reconciliation tools.