Full answer
Problem
Given nums, return every distinct triplet [a, b, c] of values at different indices with a + b + c == 0. The result must not contain duplicate triplets.
Example: [-1, 0, 1, 2, -1, -4] gives [[-1, -1, 2], [-1, 0, 1]].
Constraints: 0 <= len(nums) <= 3000, values from -10^5 to 10^5.
Brute force
Three nested loops and a set of sorted triplets: O(n^3), too slow for 3,000 (about 4.5 billion checks).
Optimal approach
- Sort
nums. - For each
i:- If
nums[i] > 0, stop: all later values are positive too. - If
nums[i] == nums[i - 1], skip, to avoid repeating the same first value. - Set
lo = i + 1,hi = n - 1. Whilelo < hi, compute the sum. Too small:lo += 1. Too large:hi -= 1. Zero: record it, move both pointers, and skip equal values atlo.
- If
Why it works
For a fixed first value, the remaining problem is Two Sum on a sorted range. If the sum is too small, the current lo cannot pair with any value at or below hi to reach zero, so it can be discarded; the mirror argument applies to hi. Skipping equal first and second values means each distinct triplet is produced once (equal third values are then forced, so they need no separate skip).
Complexity
Sorting O(n log n) plus O(n) two-pointer work for each of n first values: O(n^2) time. O(1) extra space besides the sorted copy and output (Python's sorted makes an O(n) copy; sorting in place avoids it).
Code
def three_sum(nums):
"""All unique triplets [a, b, c] with a + b + c == 0. O(n^2) time."""
nums = sorted(nums)
n = len(nums)
result = []
for i in range(n - 2):
if nums[i] > 0:
break # smallest value positive: no zero sum left
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate first values
lo, hi = i + 1, n - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 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 duplicate second values
return result
if __name__ == "__main__":
assert three_sum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]
assert three_sum([0, 1, 1]) == []
assert three_sum([0, 0, 0, 0]) == [[0, 0, 0]]
assert three_sum([]) == []
assert three_sum([-2, 0, 1, 1, 2]) == [[-2, 0, 2], [-2, 1, 1]]
print("all tests passed")Save as a17_three_sum.py and run python3 a17_three_sum.py. It prints all tests passed (Python 3.13.5).
Edge cases
Fewer than three values. All zeros (one triplet [0, 0, 0]). Many duplicates. No solution (empty list). Large values: Python integers do not overflow, but in fixed-width languages the sum of three values near the limit might.
Pattern
Sort then fix one element and use two pointers. It generalises to k-Sum by recursion down to Two Sum, with O(n^(k - 1)) time. A hash-set version is also O(n^2) but makes duplicate handling harder.
def three_sum(nums):
"""All unique triplets [a, b, c] with a + b + c == 0. O(n^2) time."""
nums = sorted(nums)
n = len(nums)
result = []
for i in range(n - 2):
if nums[i] > 0:
break # smallest value positive: no zero sum left
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate first values
lo, hi = i + 1, n - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 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 duplicate second values
return result
if __name__ == "__main__":
assert three_sum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]
assert three_sum([0, 1, 1]) == []
assert three_sum([0, 0, 0, 0]) == [[0, 0, 0]]
assert three_sum([]) == []
assert three_sum([-2, 0, 1, 1, 2]) == [[-2, 0, 2], [-2, 1, 1]]
print("all tests passed")Sort, fix the first element, two pointers on the rest, skipping duplicates for the first and second values.
Complexity
Time: O(n^2). Space: O(1) extra besides the sorted copy and output. The early break when nums[i] > 0 is an optimisation only; the bound stays O(n^2).
By level
Fresher: Explains the brute force, then sorting with two pointers, and traces the example to show how duplicates are skipped. Should explain why sorting comes first.
Mid: Justifies pointer moves, handles all duplicate cases and generalises to 3Sum closest. Skips duplicates at both levels without missing triplets.
Senior: Generalises to k-Sum, discusses the conjectured lower bound for 3Sum, overflow in other languages and hash-based alternatives. Can explain why a hash set version is harder to deduplicate.
Key points
- Sort first
- Fix one value and run Two Sum with two pointers on the rest
- Skip duplicates for the first and second values
- Break early once the first value is positive
- O(n^2) time
Common mistakes
- Producing duplicate triplets
- Skipping duplicates before the first use instead of after
- Returning indices when values were asked
- Using three loops
Follow-ups
- How would you solve 3Sum closest to a target?
- How does this generalise to 4Sum?
- Can 3Sum be solved faster than O(n^2) in general?
Tips
- Reduce to Two Sum explicitly
- Explain the duplicate-skipping rule with an example
- Mention the early break
Evaluation rubric
- Correct O(n^2) algorithm
- No duplicates in output
- Correct pointer movement reasoning
- Handles edge cases