Problem 7 · Two Pointers & Sliding Window
3Sum
01Problem
Return all unique triplets in nums that sum to zero.
02Key insight
Sort, fix one element, and run two-pointer Two Sum on the remainder. Sorting also makes de-duplication a matter of skipping equal neighbours.
03Solution
Try it first.
TimeO(n^2)
SpaceO(1) extra (excluding sort/output)
tests.py · 3 passing
tests.pypython3 lines
assert three_sum([-1,0,1,2,-1,-4]) == [[-1,-1,2],[-1,0,1]]
assert three_sum([0,0,0,0]) == [[0,0,0]]
assert three_sum([0,1,1]) == []04Staff-level follow-up
Generalise to k-sum? Recurse down to the 2-sum two-pointer base case for O(n^(k-1)); for k=4 a pair-sum hash map can trade memory for speed.