Intuition
The problem asks to find all unique triplets in the given array such that the sum of the three elements is equal to zero. The solution set must not contain duplicate triplets.
Approach
The provided solution uses a two-pointer approach along with sorting the array. The idea is to fix one element (nums[i]) and use two pointers (left and right) to find the other two elements such that their sum equals zero.
Sort the array nums to make it easier to find unique triplets.
Iterate through the sorted array, fixing one element nums[i].
Use two pointers (left and right) to find the other two elements. Adjust the pointers based on the sum of the three elements:
If the sum is greater than zero, move the right pointer to the left.
If the sum is less than zero, move the left pointer to the right.
If the sum is zero, add the triplet to the result and move the pointers while skipping duplicate elements.
Return the result.
Complexity
- Time complexity:
The time complexity of this solution is O(n^2), where n is the length of the input array nums. The dominant factors are the sorting step (O(n log n)) and the two-pointer iteration (O(n)).
- Space complexity:
The space complexity is O(1), as the solution uses only a constant amount of space to store the result.
Code
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
stack=[]
nums = sorted(nums)
for i,a in enumerate(nums):
if i>0 and a==nums[i-1]:
continue
left,right=i+1,len(nums)-1
while left < right:
threesum = nums[i] + nums[left] + nums[right]
if threesum > 0:
right-=1
elif threesum < 0:
left+=1
else:
stack.append([nums[i],nums[left],nums[right]])
left+=1
while nums[left] == nums [left-1] and left < right:
left+=1
return stack