Medium
3Sum
š¶ The 5-Year-Old Summary
Find all triplets that add up to zero! [-1,0,1,2,-1,-4] ā [-1,-1,2], [-1,0,1]! Each number can only be used once per triplet!
š® Interactive Visualizer
nums = [-1, 0, 1, 2, -1, -4]
Triplets found:
š§ The Brain Hack
Sort + Two Pointers! Fix one number, use two pointers for the other two. Skip duplicates! [-1,-1,2] and [-1,0,1] = -1+0+1=0 and -1+-1+2=0!
š» The Clean Solution
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
# Skip duplicates
if i > 0 and nums[i] == nums[i-1]:
continue
# Two pointers
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return result
# [-1,0,1,2,-1,-4] ā [[-1,-1,2],[-1,0,1]]
Time: O(n²)
Space: O(log n) for sorting