3Sum
Difficulty: Medium · Pattern: Two Pointers · LeetCode #15
Given an integer array nums, return every distinct triplet of values [a, b, c] taken from three different positions with a + b + c = 0. The result must not contain the same triplet twice (as a multiset). Order of triplets and of values within them doesn't matter.
Examples
text
nums = [-2, 0, 1, 1, 2] → [[-2, 0, 2], [-2, 1, 1]]
nums = [0, 0, 0, 0] → [[0, 0, 0]]
nums = [1, 2, -4] → []Hints
- Sort first. Then fix the first element
nums[i]and look for a pair summing to−nums[i]in the rest. - That inner search is Two Sum II: two pointers.
- To avoid duplicates, skip equal values for
i, and skip equal values after finding a triplet.
Approach
Sort the array. For each index i (skipping nums[i] equal to nums[i−1]), run two pointers on i+1 … n−1 looking for sum −nums[i]. On a hit, record it, then move both pointers past any repeated values. Early exit: once nums[i] > 0, no triplet can sum to 0.
Total: O(n log n) sort + O(n²) for the loops.
Complexity
Time: O(n²). Space: O(1) extra (ignoring output and sort internals).
Python solution
def threeSum(nums):
nums.sort()
n, res = len(nums), []
for i in range(n - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, n - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append([nums[i], nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while l < r and nums[r] == nums[r + 1]:
r -= 1
return resJavaScript solution
function threeSum(nums) {
nums.sort((a, b) => a - b);
const res = [], n = nums.length;
for (let i = 0; i < n - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] === nums[i - 1]) continue;
let l = i + 1, r = n - 1;
while (l < r) {
const s = nums[i] + nums[l] + nums[r];
if (s < 0) l++;
else if (s > 0) r--;
else {
res.push([nums[i], nums[l], nums[r]]);
l++; r--;
while (l < r && nums[l] === nums[l - 1]) l++;
while (l < r && nums[r] === nums[r + 1]) r--;
}
}
}
return res;
}