Statementâ–¼
Given an array nums
of nums[a]
, nums[b]
, nums[c]
, nums[d]
] such that:
0≤ a
,b
,c
,d
<n a
,b
,c
, andd
are distinct.nums[a]
+nums[b]
+nums[c]
+nums[d]
= target
You may return the answer in any order.
Constraints:
1≤ nums.length
≤200 −109≤ nums[i]
≤109 −109≤ target
≤109
Solution
The problem involves finding all unique sets of four numbers in an array that sum up to a specified target. The solution combines sorting and two pointer techniques to find these quadruplets. By sorting the array and strategically moving pointers, the solution ensures that only valid and unique quadruplets are considered, optimizing it.
Now, let’s walk through the steps of the solution.
Check if the length ofÂ
nums
 is less than4 , and return an empty result since it’s impossible to form a quadruplet.SortÂ
nums
 to make finding and managing combinations that add to the target easier.Create a listÂ
result
 to store all the valid quadruplets that sum up to the target.Iterate over the sorted array using indexÂ
i
 to pick the first number of the quadruplet.Skip duplicate values forÂ
i
 to prevent considering the same quadruplet multiple times.For each selectedÂ
i
, iterate over the array using indexÂj
 (starting fromÂi + 1
) to pick the second number of the quadruplet.Skip duplicate values forÂ
j
 to prevent considering the same quadruplet multiple times.Set two pointers:Â
left
 (just afterÂj
) andÂright
 (at the end of the array).Calculate the sum of the four numbers:Â
nums[i]
,Ânums[j]
,Ânums[left]
, andÂnums[right]
.If the sum is less than the target, move theÂ
left
 pointer to the right to increase the sum.If the sum exceeds the target, move theÂ
right
 pointer to the left to decrease the sum.If the sum matches the target, add the quadruplet to theÂ
result
.After finding a valid quadruplet, move bothÂ
left
 andÂright
 pointers inward.Skip duplicate values atÂ
left
 andÂright
 to avoid adding the same quadruplet again.Continue adjusting pointers and checking sums until theÂ
left
 pointer is less than theÂright
 pointer.After all possible combinations have been checked, return theÂ
result
, containing all unique quadruplets that sum up to the target.
Let’s look at the following illustration to get a better understanding.