Find All Triplets with Sum Zero in Python
This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.
Python code
29 linesdef find_triplets(nums):
nums.sort()
n = len(nums)
triplets = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
triplets.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return triplets
if __name__ == "__main__":
test_array = [-1, 0, 1, 2, -1, -4]
result = find_triplets(test_array)
print(f"Array: {test_array} → sorted: {sorted(test_array)}")
print(f"Unique triplets summing to zero: {result}")
Output
Array: [-1, 0, 1, 2, -1, -4] → sorted: [-4, -1, -1, 0, 1, 2]
Unique triplets summing to zero: [[-1, -1, 2], [-1, 0, 1]]
How it works
The function first sorts the input array to enable the two-pointer approach. For each element as a potential first value, it uses two pointers (left and right) to find pairs that sum to the negative of that element. Skipping duplicate first values and duplicate elements after a match ensures unique triplets only. The algorithm runs in O(n^2) time and O(1) extra space (excluding output).
Common mistakes
- Forgetting to sort the input before using two pointers.
- Not skipping duplicate values, leading to repeated triplets.
- Off-by-one errors when advancing pointers after a match.
Variations
- Use a hash set approach to find pairs for each element (O(n^2) time but no sorting needed).
- Use itertools.combinations for a simple but less efficient O(n^3) solution.
Real-world use cases
- Finding three numbers that sum to a target in financial portfolio balancing.
- Identifying triplets of sensor readings that indicate a system state in IoT analytics.
- Grouping products by combined price thresholds in e-commerce discount rules.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.