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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

29 lines
Python 3.9+
def 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

stdout
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

  1. Use a hash set approach to find pairs for each element (O(n^2) time but no sorting needed).
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.