# Leetcode 4Sum problem solution in C++

Feb 19, 2023

In the Leetcode 4Sum problem solution in C++ programming Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.

## Leetcode 4Sum problem solution in C++ programming

``````class Solution
{
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
std::set<std::vector<int>> res;

std::sort(nums.begin(), nums.end());
for (int a = 0; a < nums.size(); a++)
{
for (int b = a + 1; b < nums.size(); b++)
{
long long temp = (long long)target - nums[a] - nums[b];
int slow = b + 1;
int fast = nums.size() - 1;
while (slow < fast)
{
if (nums[slow] + nums[fast] == temp)
{
res.insert({nums[a], nums[b], nums[slow], nums[fast]});
}

if (nums[slow] + nums[fast] > temp)
{
fast--;
}
else
{
slow++;
}
}
}
}

return {res.begin(), res.end()};
}
};``````

#### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.