📌 Problem
[LeetCode] 15. 3Sum

📌 Solution
Idea
- Fix the first pointer
i and move the other two l, r with a while loop to find valid triplets
- Continue searching by shifting
l right and r left even after finding a sum of zero, since there may be other number combinations that also add up to zero
- Skip repeated values of
i, l, and r to avoid duplicate triplets
Code
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
res = []
for i in range(n-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, n-1
while l < r:
total = nums[i] + nums[l] + nums[r]
if total == 0:
res.append([nums[i], nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
r -= 1
while l < r and nums[r] == nums[r+1]:
r -= 1
elif total < 0:
l += 1
else:
r -= 1
return res