Three Number Sum (2 Pointer) in Python
Justin Bermudez
Posted on August 30, 2020
Three Number Sum is a popular problem found on leetcode where you are given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Link to problem at leetcode: here
Full Python Solution Here:
def threeNumberSum(array, targetSum):
array.sort()
result = []
for i in range(len(array) - 2):
left = i + 1
right = len(array) - 1
while left < right:
currSum = array[i] + array[left] + array[right]
if currSum == targetSum:
res.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif currSum < targetSum:
left += 1
elif currSum > targetSum:
right -= 1
return result
💖 💪 🙅 🚩
Justin Bermudez
Posted on August 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.