1. Sort the given array nums
in non-decreasing order.
2. Initialize an empty list result
to store the quadruplets.
3. Iterate over the array with two nested loops (indices i
and j
) to fix the first two elements.
Inside the nested loops, use two pointers (left
and right
) to find the remaining two elements.
Initialize left
to j + 1
and right
to len(nums) - 1
.
While left
is less than right
:
Calculate the current sum as nums[i] + nums[j] + nums[left] + nums[right]
.
If the sum is equal to the target:
Add [nums[i], nums[j], nums[left], nums[right]]
to the result
.
Move left
to the right to avoid duplicates.
Move right
to the left to avoid duplicates.
If the sum is less than the target, increment left
.
If the sum is greater than the target, decrement right
.
4. Continue the outer loops, making sure to skip duplicate values to avoid duplicate quadruplets.
5. Return the result
list containing all unique quadruplets.
This algorithm ensures that the solution set contains unique quadruplets and has a time complexity of O(n^3)
due to the three nested loops. Sorting the array at the beginning contributes O(n log n)
to the overall time complexity.