DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Three Number Sum (2 Pointer) in Python

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

Top comments (1)

Collapse
 
qm3ster profile image
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]?)