DEV Community is a community of 698,942 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Three Number Sum (2 Pointer) in Python

Justin Bermudez

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
``````

Discussion (1)

Mihail Malo
1. What is the definition of "unique triplets"?
2. Are all the input integers unique? (i.e, will we never get `[-5, -5, -5, -5, 10, 10]`?)