Problem
Given an array S
of n
integers, find all unique quadruplets (a, b, c, d)
in S
such that a + b + c + d = target
. The quadruplets must be in non-descending order, and the solution set must not contain duplicate quadruplets.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
Examples
Example 1:
Input: nums = [1, 0, -1, 0, -2, 2]
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Explanation: The pair (6, 7) gives the highest product of 42.
Also make sure that the solution set is lexicographically sorted.
Solution[i] < Solution[j] iff Solution[i][0] < Solution[j][0] OR (Solution[i][0] == Solution[j][0] AND ... Solution[i][k] < Solution[j][k])
Solution
Method 1 - Sorting and Two pointer technique
Here is the approach:
- Sort the Array: Start by sorting the array. This will help ensure the quadruplets are generated in non-descending order.
- Nested Loop for Quadruplets: Use four nested loops to find quadruplets that sum to the target:
- The outer two loops fix the first two elements of the quadruplet.
- The inner two loops use a two-pointer approach to find the remaining two elements that sum to
target - (a + b)
.
- Check for Duplicates: Use sets or condition checks to avoid duplicate quadruplets.
Code
Java
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // Avoid duplicates
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue; // Avoid duplicates
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++; // Avoid duplicates
while (left < right && nums[right] == nums[right + 1]) right--; // Avoid duplicates
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 0, -1, 0, -2, 2};
int target = 0;
List<List<Integer>> quadruplets = sol.fourSum(nums, target);
for (List<Integer> quadruplet : quadruplets) {
System.out.println(quadruplet);
}
// Expected output:
// (-2, -1, 1, 2)
// (-2, 0, 0, 2)
// (-1, 0, 0, 1)
}
}
Python
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = []
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue # Avoid duplicates
for j in range(i + 1, len(nums) - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue # Avoid duplicates
left, right = j + 1, len(nums) - 1
while left < right:
four_sum = nums[i] + nums[j] + nums[left] + nums[right]
if four_sum == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1 # Avoid duplicates
while left < right and nums[right] == nums[right + 1]:
right -= 1 # Avoid duplicates
elif four_sum < target:
left += 1
else:
right -= 1
return result
# Example usage
sol = Solution()
nums = [1, 0, -1, 0, -2, 2]
target = 0
quadruplets = sol.fourSum(nums, target)
for quadruplet in quadruplets:
print(quadruplet)
# Expected output:
# [-2, -1, 1, 2]
# [-2, 0, 0, 2]
# [-1, 0, 0, 1]
Complexity
- ⏰ Time complexity:
O(n^3)
, wheren
is the number of elements in the array. This is because of the three nested loops iterating through the sorted array. - 🧺 Space complexity:
O(k)
, wherek
is the number of unique quadruplets.