4Sum
4Sum is a medium arrays & hashing problem solved with the two pointer pattern.
The best approach, optimal (sort + two loops + two pointers), runs in O(n³) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (all quadruples + set) up.
Problem
You are given an integer array nums and an integer target. Return every distinct group of four values [a, b, c, d] taken from four different positions of nums such that a + b + c + d == target.
Two groups count as the same if they contain the same values (as a multiset), so each value group appears only once in the answer. The groups, and the values inside a group, may be returned in any order.
Examples
Example 1
- Input
nums = [2, -1, 0, 3, -2, 1], target = 2- Output
[[-2, -1, 2, 3], [-2, 0, 1, 3], [-1, 0, 1, 2]]- Why
- Each listed group of four values adds up to 2, and no other distinct group does.
Example 2
- Input
nums = [5, 5, 5, 5, 5], target = 20- Output
[[5, 5, 5, 5]]- Why
- Many index choices give the same values, but the quadruplet is reported once.
Example 3
- Input
nums = [1, 2, 3], target = 6- Output
[]- Why
- Fewer than four numbers, so no quadruplet exists.
Constraints
1 <= nums.length <= 200-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (all quadruples + set) | O(n⁴) | O(q) |
| Optimal (sort + two loops + two pointers) | O(n³) | O(1) |
1Brute force (all quadruples + set)
O(n⁴)There are about n⁴ / 24 index quadruples, each checked in O(1).O(q)The set holds the q distinct answers.Sort the array, try every choice of four indices i < j < k < l, and keep the value tuples whose sum equals the target in a set so repeated value groups are stored once.
- Sort
numsso every tuple comes out in non-decreasing order. - Four nested loops over i < j < k < l.
- If the 64-bit sum equals target, add the tuple to a set.
- Return the set as a list.
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
Set<List<Integer>> seen = new LinkedHashSet<>();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
for (int k = j + 1; k < n; k++)
for (int l = k + 1; l < n; l++) {
long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];
if (sum == target) seen.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
}
return new ArrayList<>(seen);
}
}class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
seen = set()
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
for l in range(k + 1, n):
if nums[i] + nums[j] + nums[k] + nums[l] == target:
seen.add((nums[i], nums[j], nums[k], nums[l]))
return [list(t) for t in seen]class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
set<vector<int>> seen;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
for (int k = j + 1; k < n; k++)
for (int l = k + 1; l < n; l++) {
long long sum = (long long)nums[i] + nums[j] + nums[k] + nums[l];
if (sum == target) seen.insert({nums[i], nums[j], nums[k], nums[l]});
}
return vector<vector<int>>(seen.begin(), seen.end());
}
};function fourSum(nums, target) {
nums.sort((a, b) => a - b);
const n = nums.length;
const seen = new Map();
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
for (let k = j + 1; k < n; k++)
for (let l = k + 1; l < n; l++) {
if (nums[i] + nums[j] + nums[k] + nums[l] === target) {
const t = [nums[i], nums[j], nums[k], nums[l]];
seen.set(t.join(','), t);
}
}
return [...seen.values()];
}2Optimal (sort + two loops + two pointers)
O(n³)n² choices of (i, j), each followed by an O(n) two-pointer sweep; sorting is O(n log n).O(1)Only pointers besides the output (and the sort's own stack).After sorting, fix the first value nums[i] and the second value nums[j]. The remaining pair must sum to target - nums[i] - nums[j], which two pointers find in one linear sweep of the rest of the array. Skipping equal neighbours at every level keeps each value group unique without a set.
- Sort
nums. - For each i, skip it if
nums[i] == nums[i - 1]. - For each j > i, skip it if
j > i + 1andnums[j] == nums[j - 1]. - Set lo = j + 1, hi = n - 1 and compute the 64-bit sum.
- Sum too small → lo++; too big → hi--; equal → record, then move both pointers past equal values.
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> out = new ArrayList<>();
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int lo = j + 1, hi = n - 1;
while (lo < hi) {
long sum = (long) nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum < target) lo++;
else if (sum > target) hi--;
else {
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--;
}
}
}
}
return out;
}
}class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
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:
s = nums[i] + nums[j] + nums[lo] + nums[hi]
if s < target:
lo += 1
elif s > target:
hi -= 1
else:
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
return outclass Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> out;
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int lo = j + 1, hi = n - 1;
while (lo < hi) {
long long sum = (long long)nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum < target) lo++;
else if (sum > target) hi--;
else {
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--;
}
}
}
}
return out;
}
};function fourSum(nums, target) {
nums.sort((a, b) => a - b);
const n = nums.length;
const out = [];
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 lo = j + 1, hi = n - 1;
while (lo < hi) {
const sum = nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum < target) lo++;
else if (sum > target) hi--;
else {
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--;
}
}
}
}
return out;
}Edge cases to test
- Fewer than four elements
- All values equal (one answer, many index choices)
- Sums that overflow a 32-bit int, like four values near 10^9
- Negative target
Hints
Hint 1
Sorting makes duplicates sit next to each other, so they are easy to skip.
Hint 2
Fix the first two values with two loops. What is left is a two-sum on a sorted range.
Hint 3
Use two pointers for the last two values and do the arithmetic in 64-bit.
FAQ
What is the best time complexity for 4Sum?
Optimal (sort + two loops + two pointers) runs in O(n³) time and O(1) extra space. n² choices of (i, j), each followed by an O(n) two-pointer sweep; sorting is O(n log n).
Which pattern does 4Sum use?
It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.
Is there a brute force solution for 4Sum?
Yes. Brute force (all quadruples + set) takes O(n⁴) time and O(q) space. Sort the array, try every choice of four indices i < j < k < l, and keep the value tuples whose sum equals the target in a set so repeated value groups are stored once.
Which edge cases should I test for 4Sum?
Fewer than four elements; All values equal (one answer, many index choices); Sums that overflow a 32-bit int, like four values near 10^9; Negative target.