Leetcode: 4Sum

4Sum

Similar Problems:

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

```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]
]
```

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

```## Blog link: https://code.dennyzhang.com/4sum
## Basic Idea: sort the list, then 4 indices. i, j, l, r
## Complexity: Time O(n*n*n), Space O(1)
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
res = []
for i in xrange(len(nums)-3):
if i>0 and nums[i] == nums[i-1]:
continue

for j in range(i+1, len(nums)-2):
if j>i+1 and nums[j] == nums[j-1]:
continue

l = j+1
r = len(nums)-1
while l<r:
val = nums[i] + nums[j] + nums[l] + nums[r]
if val > target:
r -= 1
elif val < target:
l += 1
else:
res.append([nums[i], nums[j], nums[l], nums[r]])
while l<r and nums[l] == nums[l+1]:
l += 1
while l<r and nums[r] == nums[r-1]:
r -= 1
l, r = l+1, r-1
return res
```

Share It, If You Like It.