---
tags: data_structure_python
---
# 3sum
## Solution 1
- Time complexity: O(n³)
- Space complexity: O(n)
```python=
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if n < 3: return []
res = []
sorted_nums = list(sorted(nums))
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if sorted_nums[i] + sorted_nums[j] + sorted_nums[k] == 0:
if [sorted_nums[i], sorted_nums[j], sorted_nums[k]] not in res:
res.append([sorted_nums[i], sorted_nums[j], sorted_nums[k]])
return res
```
# Solution 2
- Binary search (by sorting first)
- Time complexity: O(n²)
- Space complexity: O(n)
```python=
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# Time complexity: O(n^2)
# Space complexity: O(n)
n = len(nums)
if n < 3: return []
res = []
sorted_nums = list(sorted(nums))
for i in range(n-2):
if i > 0 and sorted_nums[i-1] == sorted_nums[i]: # Skip already found threeSum for a fixed sorted_nums[i]
continue
l, r = i+1, n-1
while l < r:
threeSum = sorted_nums[i] + sorted_nums[l] + sorted_nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
res.append([sorted_nums[i], sorted_nums[l], sorted_nums[r]])
l += 1
while sorted_nums[l] == sorted_nums[l-1] and l < r: # Find all unique threeSum for a fixed sorted_nums[i]
l += 1
return res
```