---
# System prepended metadata

title: '[Three Sum](https://leetcode.com/problems/3sum/solution/)'
tags: [Leetcode, Two Pointers, Medium]

---

# [Three Sum](https://leetcode.com/problems/3sum/solution/)
###### tags: `Leetcode`, `Medium`, `Two Pointers`

## Approach
* Sort the input list in ascending order and initialize a result list
* Iterate through the list
    * If current value is same as value at previous index; continue
    * Initialize left and right to `index + 1` and `len(nums) - 1`
    * If the sum of current number, `nums[left]` and `nums[right]` is equal to 0, add the three numbers to result array, increment left by 1
        * if `nums[left]` == `nums[left - 1]` then increment left by 1
    * If sum < 0; increment left by 1
    * If sum > 0; decrement right by 1
* Return result

## Asymptotic Analysis
### Time Complexity: **O(N<sup>2</sup>)**
### Space Complexity: **O(N)**

## Code
``` python
from typing import List


class ThreeSum:

    @staticmethod
    def threeSum(nums: List[int]) -> List[List[int]]:
        nums.sort()
        result = []
        for index, number in enumerate(nums):
            if index > 0 and number == nums[index - 1]:
                continue
            left, right = index + 1, len(nums) - 1
            while left < right:
                sum = number + nums[left] + nums[right]
                if sum > 0:
                    right -= 1
                elif sum < 0:
                    left += 1
                else:
                    result.append([number, nums[left], nums[right]])
                    left += 1
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
        return result


numbers = [-1,0,1,2,-1,-4]
print(ThreeSum.threeSum(numbers))
```