3 sum


description
accepted answer

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i, a in enumerate(nums):
            # we dont want duplicates
            if i > 0 and a == nums[i - 1]:
                continue

            l, r = i+1, len(nums) - 1 
            while l < r:
                threeSum = a + nums[l] + nums[r]
                # too big, go left to go small
                if threeSum > 0:
                    r -= 1
                elif threeSum < 0:
                # too small, go right to go small
                    l += 1
                else:
                    # add
                    res.append([a, nums[l], nums[r]])
                    # go left to go to another iteration
                    l += 1
                    # go left if duplicate
                    while nums[l] == nums[l - 1] and l < r:
                        l += 1
        return res