Find all unique quadruplets in the array which gives the sum of target.
Problem Statement
Examples
Input: nums = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Explanation: Combining the input according to 4 Sum logic yields [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]].
Input: nums = [2, 2, 2, 2, 2], target = 8
Output: [[2, 2, 2, 2]]
Explanation: Combining the input according to 4 Sum logic yields [[2, 2, 2, 2]].
Complexity
Time Complexity: O(N³)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
By sorting the array, we fix two pointers (i, j) in nested loops and use two pointers (left, right) for the remaining pair. This reduces the search from O(N⁴) brute force to O(N³). Duplicate skipping ensures uniqueness.
Step-by-Step Approach
- Sort
numsin ascending order. - Outer loop
ifrom0ton - 4, skipping duplicates. - Inner loop
jfromi + 1ton - 3, skipping duplicates. - Run two pointers
left = j + 1, right = n - 1. - When
sum === target, record quadruplet and skip inner duplicates. - Return
result.
Optimal Implementation (JavaScript)
function fourSum(nums, target) {
nums.sort((a, b) => a - b);
const result = [];
const n = nums.length;
for (let i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
for (let j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] === nums[j - 1]) continue;
let left = j + 1, right = n - 1;
while (left < right) {
const sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum === target) {
result.push([nums[i], nums[j], nums[left], nums[right]]);
while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < target) left++;
else right--;
}
}
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Length < 4: returns [].
- Large target values.
- Array of duplicate numbers.