Find every triple that sums to zero, with no repeats. Sort, fix one number, then close in from both ends with two pointers.
▼The problem
LeetCode 15 (Medium). Given a list of numbers, return every unique triplet [a, b, c], taken from three different positions, with a + b + c = 0.
Example (from LeetCode): [-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]].
def three_sum(nums):
nums.sort()
out = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # same anchor
lo, hi = i + 1, len(nums) - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
out.append([nums[i], nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip repeats
return outTRY IT ON LEETCODE ▶The solution
def three_sum(nums):
nums.sort()
out = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # same anchor
lo, hi = i + 1, len(nums) - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
out.append([nums[i], nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip repeats
return outTranscript
Three Sum. You get a list of numbers. Find every group of three, from different positions, that adds up to zero. Each triplet counts only once, even when the list has repeats.
Take minus one, zero, one, two, minus one, minus four. Two triplets balance: minus one, minus one, two; and minus one, zero, one. The other minus one with zero and one repeats a triplet, so it counts once.
The naive way tries every group of three with three nested loops: twenty groups for six numbers, and the work grows with n cubed. And duplicates slip through, so they need cleaning up.
The trick is to sort first. Then pin one number as the anchor. Put one hand just after it, and the other at the far end. If the sum is below zero, the left hand moves right, to a bigger number. If it's above zero, the right hand moves left, to a smaller one. Every step rules out one number for good.
Sorted, the list is minus four, minus one, minus one, zero, one, two. Anchor minus four: every sum stays negative, so the left hand walks all the way in. Anchor minus one: minus one, minus one, two makes zero. Record it. Minus one, zero, two is too big, so the right hand steps back. Minus one, zero, one. Record it. The next minus one is the same anchor, so skip it. Anchor zero: zero, one, two is too big, and the hands meet. Done: two triplets, in eight checks instead of twenty.
In code: sort, then loop over the anchors, skipping repeated ones. Walk the two pointers inward until they meet. Below zero, move the left one; above zero, the right one. On zero, record the triplet, then step the left pointer past any repeats.
Sorting costs n log n. Then each anchor gets one inward sweep, so the time is n squared, down from n cubed. Apart from the sort, the extra space is constant.
Sort, pin an anchor, squeeze the hands. That's Three Sum.