w3resource

Python: Find unique triplets whose three elements gives the sum of zero from an array of n integers


Zero Sum Triplets

Write a Python program to identify unique triplets whose three elements sum to zero from an array of n integers.

Visual Presentation:

Python: Find unique triplets whose three elements gives the sum of zero from an array of n integers

Sample Solution:

Python Code:

# Define a function named 'three_sum' that takes a list of numbers 'nums' as a parameter.
def three_sum(nums):
    # Initialize an empty list to store the results.
    result = []
    # Sort the input list in ascending order.
    nums.sort()
    
    # Iterate through the list up to the third-to-last element.
    for i in range(len(nums) - 2):
        # Skip duplicate values at the current position.
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        
        # Set two pointers, 'l' and 'r', to find the other two elements in the triplet.
        l, r = i + 1, len(nums) - 1
        
        # Perform a two-pointer search to find triplets with the sum equal to zero.
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            
            if s > 0:
                r -= 1
            elif s < 0:
                l += 1
            else:
                # Found a triplet with the sum equal to zero, add it to the result.
                result.append((nums[i], nums[l], nums[r]))
                
                # Remove duplicates in the left and right pointers.
                while l < r and nums[l] == nums[l + 1]:
                    l += 1
                while l < r and nums[r] == nums[r - 1]:
                    r -= 1
                
                # Move the pointers towards the center.
                l += 1
                r -= 1
    
    # Return the final result containing unique triplets.
    return result

# Create a list of numbers.
x = [1, -6, 4, 2, -1, 2, 0, -2, 0]

# Call the 'three_sum' function with the list and print the result.
print(three_sum(x))

Sample Output:

[(-6, 2, 4), (-2, 0, 2), (-1, 0, 1)]

Explanation:

The above code defines a function "three_sum()" that takes a list of numbers as input. It finds unique triplets in the list whose sum is equal to zero. The function uses a sorted list and employs a two-pointer approach to efficiently search for triplets. The code then calls this function with a specific list of numbers and prints the resulting unique triplets.

Flowchart:

Flowchart: Python - Find unique triplets whose three elements gives the sum of zero from an array of n integers

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove and print every third number from a list of numbers until the list becomes empty.
Next: Write a Python program to create the combinations of 3 digit combo.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.