## 4Sum

06/25/2016 Array Hash Table Two Pointers

## Question

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


## Solution

Result: Accepted Time: 24ms

Here should be some explanations.

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums,int target) {
vector<vector<int>> ret;
sort(nums.begin(), nums.end());
const int n = nums.size();
for (int j = 0; j < n - 3;)
{
for (int i =  j + 1; i < n - 2;)
{
int rest = target - nums[i] - nums[j],left = i + 1,right = n - 1;;
if(rest < nums[i+1] + nums[i+2])
break;
while (left < right)
{
if(rest > nums[right]+nums[right-1])
break;
if ((nums[left] + nums[right]) == rest)
ret.push_back(vector<int>{nums[j],nums[i],nums[left],nums[right]});
if ((nums[left] + nums[right]) < rest)
for(++left;left < right && nums[left-1] == nums[left];++left);
else
for(--right;left < right && nums[right+1] == nums[right];--right);
}
for(++i;nums[i-1] == nums[i];++i);
}
for(++j;nums[j-1] == nums[j];++j);
}
return ret;
}
};



Complexity Analytics

• Time Complexity: $O(n^3)$
• Space Complexity: $O(1)$