Find all possible triplets in an array that sum to 0 - code in comments #tech #coding #leetcode

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

"""
Given an array of integers,
we need to find all unique triplets
that sum up to zero.
"""

def threeSum(nums):
# Sorting the array to allow the two pointer approach
nums.sort()
result = []

for i in range(len(nums)-2):
# Avoid duplicate triplets by skipping equal elements
if i > 0 and nums[i] == nums[i-1]:
continue

# Using two pointers on the remaining elements
left = i + 1
right = len(nums) - 1

while left < right:
current_sum = nums[i] + nums[left] + nums[right]

if current_sum == 0:
result.append([nums[i], nums[left], nums[right]])
# Avoid duplicate triplets by skipping equal elements
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
# Move the pointers to the next unique elements
left += 1
right -= 1
elif current_sum < 0:
left += 1
else:
right -= 1

return result

nums = [0, -1, 1, 2, 4, -2, 5, -2, 9, 8, -4, -4, 5, 0, 0]

print(threeSum(nums))

SelfishProgrammer
welcome to shbcf.ru