# Time: O(n^3)
# Space: O(1)
# 18. 4sum
# Edge case
'''
1. IO
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
'''
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums = sorted(nums)
result = []
for i in range(len(nums)-3):
if i==0 or nums[i] != nums[i-1]:
for j in range(i+1, len(nums)-2):
if j == i+1 or nums[j] != nums[j-1]:
left = j + 1
right = len(nums) - 1
sum = target - nums[i] - nums[j]
while left < right:
if nums[left] + nums[right] < sum:
left += 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
result.append([nums[i],nums[j],nums[left],nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left-1]:
left += 1
while left < right and nums[right] == nums[right+1]:
right -= 1
return result