Problem Description
Given an array of integers and a target value, the task is to find all unique quadruplets in the array that sum up to the target value. Each quadruplet must consist of four distinct elements from the array.
Key Insights
- Sort the array to simplify handling duplicates and employ two pointers efficiently.
- Use nested loops to fix the first two numbers and then use the two-pointer technique for the remaining two numbers.
- Carefully skip duplicates at each step to ensure all quadruplets in the result are unique.
- Manage potential overflow or large input sizes by careful index manipulation.
Space and Time Complexity
Time Complexity: O(n^3)
Space Complexity: O(n) for the output space assuming sorting space does not count.
Solution
The solution begins by sorting the input array to make duplicate elimination easier. Two nested loops are used to select the first and second elements of the quadruplet. For the remaining two numbers, the two-pointer approach is applied by initializing pointers at the start and the end of the remaining subarray. The sum of the four numbers is compared to the target:
- If the sum equals the target, the quadruplet is added to the results and the pointers move inward while skipping duplicate numbers.
- If the sum is less than the target, the left pointer is moved right to increase the sum.
- If the sum is greater than the target, the right pointer is moved left to decrease the sum. This strategy efficiently finds all unique quadruplets that meet the condition.