Given an integer array, find all unique triplets in the array that sum up to 0. Each triplet should consist of three distinct indices, and the solution set must not contain duplicate triplets.
Key Insights
Sort the array to efficiently skip duplicates and facilitate the two pointers approach.
Use a fixed pointer for the first element, and then use two additional pointers (left and right) to find pairs that sum to the negation of the fixed element.
Skip duplicate elements to ensure unique triplets.
Space and Time Complexity
Time Complexity: O(n²) where n is the number of elements in the array.
Space Complexity: O(1) extra space (ignoring the space required for the output).
Solution
We first sort the array to bring duplicates together and allow the two-pointer technique to work efficiently. Then, iterate over the array and for each element, use two pointers (one at the beginning right after the current element and one at the end of the array) to find a pair that sums with the current element to zero. Skip duplicates for the current element and within the inner loop to avoid duplicate triplets. This ensures that each valid triplet is unique and the overall runtime remains efficient.
Code Solutions
# Function to find all unique triplets that sum to zero.defthreeSum(nums):# Sort the array to facilitate finding duplicates and using two pointers. nums.sort() result =[] n =len(nums)# Iterate through the array, fixing one element at a time.for i inrange(n -2):# Skip duplicate elements for the first element.if i >0and nums[i]== nums[i -1]:continue left, right = i +1, n -1while left < right: current_sum = nums[i]+ nums[left]+ nums[right]# Check if the triplet adds up to zero.if current_sum ==0: result.append([nums[i], nums[left], nums[right]])# Skip duplicates for the second element.while left < right and nums[left]== nums[left +1]: left +=1# Skip duplicates for the third element.while left < right and nums[right]== nums[right -1]: right -=1 left +=1 right -=1elif current_sum <0: left +=1else: right -=1return result
# Example usage:#print(threeSum([-1,0,1,2,-1,-4]))