4Sum
Medium
Topics
Given an array nums of n integers and a target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] with distinct indices whose sum equals target.
The quadruplets may be returned in any order.
Example 1
Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2
Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]]
Constraints
- 1 <= nums.length <= 200
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is 3Sum with one more layer. Sort the array, fix the two outer indices with nested loops, and solve the remaining 2Sum with the standard two-pointer sweep. Sorting is what buys you both the linear inner sweep and a clean way to skip duplicates: identical values sit next to each other, so "same as previous at this level" is a single comparison. The pattern generalises to k-Sum in O(n^(k-1)).
Approach
- Sort
nums. Every quadruplet is now generated in non-decreasing order, so no post-hoc deduplication is needed. - Loop
iover the first element andjover the second. At each level, skip a value identical to the previous one at the same level — that is what prevents duplicate quadruplets. - For the remaining range, run two pointers
loandhi. Compare the four-way sum to the target: too small movesloup, too large moveshidown, equal records the quadruplet. - After recording a hit, advance both pointers past all copies of the values just used.
- Optional pruning: if the smallest four values from
ialready exceed the target, break; if the largest four are still below it, skip ahead. This is what keeps the constant small on adversarial inputs.
class Solution:
def fourSum(self, nums, target):
nums.sort()
n = len(nums)
res = []
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
lo, hi = j + 1, n - 1
while lo < hi:
total = nums[i] + nums[j] + nums[lo] + nums[hi]
if total < target:
lo += 1
elif total > target:
hi -= 1
else:
res.append([nums[i], nums[j], nums[lo], nums[hi]])
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
while lo < hi and nums[hi] == nums[hi + 1]:
hi -= 1
return resDry Run
nums = [1, 0, -1, 0, -2, 2] sorted to [-2, -1, 0, 0, 1, 2], target 0
Two fixed indices plus the two-pointer scan from 3sum, so four nested levels and
four places duplicates can leak.
answer [-2,-1,1,2] | [-2,0,0,2] | [-1,0,0,1]
This input needs none of the dedup guards -- all three still produce the correct
answer -- which makes it a poor place to learn what they do. Inputs that separate
them:
no i-level guard nums [-2,1,2,-1,0,0,-2] target -2
emits [-2,-1,0,1] twice
no j-level guard nums [0,2,0,2,-1] target 3
emits [-1,0,2,2] twice
j > 0 instead of j > i + 1
nums [-2,1,2,-1,0,0,-2] target -2
LOSES [-2,-2,0,2] -- over-suppression, not duplication
That third one is the subtle one and it fails in the opposite direction. `j > 0`
refuses any repeated value anywhere, including the second -2 that the quadruplet
[-2,-2,0,2] legitimately needs. The guard has to compare against the previous
value AT THE SAME LEVEL, which is what `j > i + 1` expresses.
The post-hit advances are a fourth guard, moving lo and hi past their own runs
after a match so the same pair is not recorded twice.
In fixed-width languages the four-way sum can overflow; accumulate in 64 bits.
And arrays shorter than 4 must yield an empty list, which `range(n - 3)` handles
by simply not iterating.Complexity
- Time — O(n^3) — two nested loops around a linear two-pointer sweep.
- Space — O(log n) to O(n), all of it the sort: the four index variables are O(1). The sort is the real cost:
Arrays.sort(int[])in Java andstd::sortin C++ recurse in place for O(log n) of stack, while Python's Timsort allocates a merge buffer for O(n). The output list is excluded by convention, being the answer rather than scratch space.
Common Pitfalls
- Skipping duplicates at only one level still emits repeats, though the page's own input does not show it — every dedup variant returns the correct answer there. Measured separating inputs: with no
i-level guard,[-2,1,2,-1,0,0,-2]at target -2 emits[-2,-1,0,1]twice; with noj-level guard,[0,2,0,2,-1]at target 3 emits[-1,0,2,2]twice. The post-hit advance on both pointers is a fourth guard. - The dedup guard must compare against the previous value at the same level:
j > i + 1, notj > 0. This one fails in the opposite direction — it over-suppresses. On[-2,1,2,-1,0,0,-2]at target -2 it loses[-2,-2,0,2], the quadruplet that legitimately uses both -2s. - In languages with fixed-width ints the four-way sum can overflow. Accumulate in a 64-bit type.
- Do not use a hash set of all pair sums as a shortcut — reconstructing index-distinct quadruplets from it is where the bugs live.
- Arrays shorter than 4 must produce an empty list, so guard the loop bounds.
Full Solution — all languages
class Solution:
def fourSum(self, candidates, target):
nums = sorted(candidates)
n = len(nums)
out = []
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
lo, hi = j + 1, n - 1
while lo < hi:
total = nums[i] + nums[j] + nums[lo] + nums[hi]
if total == target:
out.append([nums[i], nums[j], nums[lo], nums[hi]])
while lo < hi and nums[lo] == nums[lo + 1]:
lo += 1
while lo < hi and nums[hi] == nums[hi - 1]:
hi -= 1
lo += 1
hi -= 1
elif total < target:
lo += 1
else:
hi -= 1
return outimport java.util.*;
class Solution {
public List<List<Integer>> fourSum(int[] candidates, int target) {
int[] nums = candidates.clone();
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> out = new ArrayList<>();
for (int i = 0; i + 3 < n; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j + 2 < n; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int lo = j + 1, hi = n - 1;
while (lo < hi) {
long total = (long) nums[i] + nums[j] + nums[lo] + nums[hi];
if (total == target) {
out.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi]));
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
lo++;
hi--;
} else if (total < target) lo++;
else hi--;
}
}
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> fourSum(vector<int>& candidates, int target) {
vector<int> nums = candidates;
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> out;
for (int i = 0; i + 3 < n; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j + 2 < n; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int lo = j + 1, hi = n - 1;
while (lo < hi) {
long long total = (long long)nums[i] + nums[j] + nums[lo] + nums[hi];
if (total == target) {
out.push_back({nums[i], nums[j], nums[lo], nums[hi]});
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
lo++;
hi--;
} else if (total < target) lo++;
else hi--;
}
}
}
return out;
}
};/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/ var fourSum = function(candidates, target) {
const nums = candidates.slice().sort((a, b) => a - b);
const n = nums.length, out = [];
for (let i = 0; i + 3 < n; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
for (let j = i + 1; j + 2 < n; j++) {
if (j > i + 1 && nums[j] === nums[j - 1]) continue;
let lo = j + 1, hi = n - 1;
while (lo < hi) {
const total = nums[i] + nums[j] + nums[lo] + nums[hi];
if (total === target) {
out.push([nums[i], nums[j], nums[lo], nums[hi]]);
while (lo < hi && nums[lo] === nums[lo + 1]) lo++;
while (lo < hi && nums[hi] === nums[hi - 1]) hi--;
lo++;
hi--;
} else if (total < target) lo++;
else hi--;
}
}
}
return out;
};