# Time: O(n^2)
# Space:
# 15. 3Sum
# Edge case: duplicate
'''
1. IO
S = [-1, 0, 1, 2, -1, -4] →
[
[-1, 0, 1],
[-1, -1, 2]
]
2.
'''
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
target = []
for i in range(len(nums)-2):
if i == 0 or nums[i] != nums[i-1]:
j = i + 1
k = len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
# tmp = [nums[i],nums[j],nums[k]] # time-consuming
# if tmp not in target:
# target.append( tmp )
target.append([nums[i],nums[j],nums[k]])
j += 1
k -= 1
while j < k and nums[j] == nums[j-1]: # better than check if there exists in current list
j += 1
while j < k and nums[k] == nums[k+1]:
k -= 1
# while i > 0 and i < len(nums) - 2 and nums[i] == nums[i-1]:
# i += 1
return target