4Sum
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here.On this page
Revision notes
4Sum (online-test style)
Video: “4Sum” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 18. LeetCode 18, Medium. Taught as an online coding test: brute, better and optimal rounds, then the k-Sum follow-up, and each fast answer grows out of the slow one.
Return every quadruplet [a, b, c, d] from four different positions of nums with a + b + c + d == target. Each quadruplet only once, in any order.
nums = [1, 0, -1, 0, -2, 2], target = 0 -> [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
nums = [2, 2, 2, 2, 2], target = 8 -> [[2, 2, 2, 2]]
| Folder | Approach | Time | Extra space |
|---|---|---|---|
Brute-EveryQuad/ |
first, second, third, fourth, each after the one before; a hit is sorted and stored in a set found, so a repeat lands on the copy already there |
O(n⁴) | the set |
Better-HashSet/ |
Fix first and second; the rest is Two Sum: need = target - nums[first] - nums[second] - nums[third], look it up in seen (emptied for every pair), then add nums[third] |
O(n³) | O(n) |
Optimal-SortAndTwoPointers/ |
Sort; fix first and second, squeeze left and right: too small → left up, too big → right down; skip repeated first, second, left and right |
O(n³) | O(1) |
FollowUp-KSum/ |
Any k: sort once, kSum fixes one number (pick) and asks kSum for k - 1 numbers after it; at k = 2 it is the squeeze |
O(n^(k-1)) | O(k) for the calls |
Rebuild it
Fix two. Squeeze the rest. Skip the repeats, mind the overflow.
- What do I fix? Two cards,
firstandsecond. The rest is the Two Sum II squeeze with targettarget - nums[first] - nums[second]. - Which four repeats do I skip?
firstequal to the one before;secondequal to the one before, but only whensecond > first + 1(the firstsecondafterfirstmay equal it:[2, 2, 2, 2]needs that); after a hit,leftequal to the one before andrightequal to the one after. - Overflow: four numbers near a billion add up to about four billion, more than a Java / C++
intcan hold, so the sum wraps to a wrong number and a test fails (LeetCode has one:[1000000000 x4], target-294967296, answer[]). Do the sum inlong(Java) /long long(C++). Four ints always fit in a long. Python integers grow as big as they need; JavaScript numbers are exact up to about 9 quadrillion, so they are safe here. - When is
longnot enough? When numbers are multiplied, products can pass even a long; then Java’sBigInteger(Python needs nothing) is the general tool. For sums of a few ints,longis enough and much faster. - Why the squeeze never misses: if the sum is too small,
nums[left]with ANY card up torightis too small, so drop left (mirror for too big). - k-Sum: 2Sum = squeeze, 3Sum = fix one + squeeze, 4Sum = fix two + squeeze, k-Sum = fix k - 2 + squeeze. Each fixed number costs one more factor of n: O(n^(k-1)). In
kSum,pick > startis the same rule assecond > first + 1. - Imports not allowed in your test? Drop
import java.util.*;and writejava.util.beforeList,Set,HashSet,ArrayList,ArraysandCollections.
Practise it on learnwithkiriti.com (notes, code in 4 languages, Memory Pairs level 3, a mock interview with Mr. Tock, Shelf Bot animates your own code), or next to the video in the Kodee Practice Chrome extension (link in the video description).
See the pseudocode.md in each folder. Every program was compiled, run and tested.
Brute: Every Quad
R1 Brute: every quad
found = empty set
for each first:
for each second after first:
for each third after second:
for each fourth after third:
sum = the four numbers (in long)
if sum == target: sort the four, add to found
return everything in found
Why each loop starts after the one before: four different positions, and each group of positions is tried once.
Why a set: [1, 0, -1, 0, -2, 2] has two 0 cards, and a sorted quad always looks the same, so the set keeps it once.
Overflow: with plain int, [1000000000 x4] and target -294967296 wrongly finds a quad (the sum wraps); in long it is [].
Check on example 1: 6 cards = 6 × 5 × 4 × 3 ÷ 24 = 15 tries, 3 quads.
Complexity: O(n⁴) time, the set for space.
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> found = new HashSet<>();
for (int first = 0; first < nums.length; first++) {
for (int second = first + 1; second < nums.length; second++) {
for (int third = second + 1; third < nums.length; third++) {
for (int fourth = third + 1; fourth < nums.length; fourth++) {
// long: four big ints can go past the int limit (overflow)
long sum = (long) nums[first] + nums[second]
+ nums[third] + nums[fourth];
if (sum == target) {
List<Integer> quad = Arrays.asList(
nums[first], nums[second], nums[third], nums[fourth]);
Collections.sort(quad);
found.add(quad);
}
}
}
}
}
return new ArrayList<>(found);
}
}class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> found;
for (int first = 0; first < nums.size(); first++) {
for (int second = first + 1; second < nums.size(); second++) {
for (int third = second + 1; third < nums.size(); third++) {
for (int fourth = third + 1; fourth < nums.size(); fourth++) {
// long: four big ints can go past the int limit (overflow)
long long sum = (long long) nums[first] + nums[second]
+ nums[third] + nums[fourth];
if (sum == target) {
vector<int> quad = {nums[first], nums[second],
nums[third], nums[fourth]};
// sorted, so the same four numbers always look the same
sort(quad.begin(), quad.end());
found.insert(quad);
}
}
}
}
}
return vector<vector<int>>(found.begin(), found.end());
}
};
void print(const vector<vector<int>>& quads) {
cout << "[";
for (size_t q = 0; q < quads.size(); q++) {
cout << (q ? ", [" : "[") << quads[q][0] << ", " << quads[q][1] << ", " << quads[q][2] << ", " << quads[q][3] << "]";
}
cout << "]" << endl;
}def fourSum(nums, target):
found = set()
for first in range(len(nums)):
for second in range(first + 1, len(nums)):
for third in range(second + 1, len(nums)):
for fourth in range(third + 1, len(nums)):
sum = nums[first] + nums[second] + nums[third] + nums[fourth]
if sum == target:
# sorted, so the same four numbers always look the same
quad = sorted([nums[first], nums[second], nums[third], nums[fourth]])
found.add(tuple(quad))
return [list(quad) for quad in found]function fourSum(nums, target) {
const found = new Map();
for (let first = 0; first < nums.length; first++) {
for (let second = first + 1; second < nums.length; second++) {
for (let third = second + 1; third < nums.length; third++) {
for (let fourth = third + 1; fourth < nums.length; fourth++) {
const sum = nums[first] + nums[second] + nums[third] + nums[fourth];
if (sum === target) {
const quad = [nums[first], nums[second], nums[third], nums[fourth]];
// sorted, so the same four numbers always look the same
quad.sort((a, b) => a - b);
found.set(quad.join(","), quad);
}
}
}
}
}
return [...found.values()];
}Better: Hash Set
R2 Better: fix first and second, then Two Sum with a hash set
found = empty set
for each first:
for each second after first:
seen = empty set
for each third after second:
need = target - nums[first] - nums[second] - nums[third] (in long)
if need in seen: sort the four, add to found
add nums[third] to seen
return everything in found
Derivation: in the brute, once first, second and third are fixed, fourth walks the rest of the row looking for ONE number, need. That is Two Sum, so remember the cards third has passed.
Two rules: seen empties for every (first, second) pair (it holds only cards after second), and check BEFORE you add (a card can’t pair with itself).
Check on example 1: 6 cards = 6 × 5 × 4 ÷ 6 = 20 checks; found still throws the repeats away.
Complexity: O(n³) time, O(n) extra space for seen (plus the set).
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> found = new HashSet<>();
for (int first = 0; first < nums.length; first++) {
for (int second = first + 1; second < nums.length; second++) {
Set<Long> seen = new HashSet<>();
for (int third = second + 1; third < nums.length; third++) {
// long: the subtraction can go past the int limit (overflow)
long need = (long) target - nums[first]
- nums[second] - nums[third];
if (seen.contains(need)) {
List<Integer> quad = Arrays.asList(
nums[first], nums[second], nums[third], (int) need);
Collections.sort(quad);
found.add(quad);
}
seen.add((long) nums[third]);
}
}
}
return new ArrayList<>(found);
}
}class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> found;
for (int first = 0; first < nums.size(); first++) {
for (int second = first + 1; second < nums.size(); second++) {
// fresh for every (first, second): only cards after second
unordered_set<long long> seen;
for (int third = second + 1; third < nums.size(); third++) {
// long: the subtraction can go past the int limit (overflow)
long long need = (long long) target - nums[first]
- nums[second] - nums[third];
if (seen.count(need)) {
vector<int> quad = {nums[first], nums[second],
nums[third], (int) need};
// sorted, so the same four numbers always look the same
sort(quad.begin(), quad.end());
found.insert(quad);
}
seen.insert(nums[third]);
}
}
}
return vector<vector<int>>(found.begin(), found.end());
}
};
void print(const vector<vector<int>>& quads) {
cout << "[";
for (size_t q = 0; q < quads.size(); q++) {
cout << (q ? ", [" : "[") << quads[q][0] << ", " << quads[q][1] << ", " << quads[q][2] << ", " << quads[q][3] << "]";
}
cout << "]" << endl;
}def fourSum(nums, target):
found = set()
for first in range(len(nums)):
for second in range(first + 1, len(nums)):
# fresh for every (first, second): only cards after second
seen = set()
for third in range(second + 1, len(nums)):
need = target - nums[first] - nums[second] - nums[third]
if need in seen:
# sorted, so the same four numbers always look the same
quad = sorted([nums[first], nums[second], nums[third], need])
found.add(tuple(quad))
seen.add(nums[third])
return [list(quad) for quad in found]function fourSum(nums, target) {
const found = new Map();
for (let first = 0; first < nums.length; first++) {
for (let second = first + 1; second < nums.length; second++) {
// fresh for every (first, second): only cards after second
const seen = new Set();
for (let third = second + 1; third < nums.length; third++) {
const need = target - nums[first] - nums[second] - nums[third];
if (seen.has(need)) {
const quad = [nums[first], nums[second], nums[third], need];
// sorted, so the same four numbers always look the same
quad.sort((a, b) => a - b);
found.set(quad.join(","), quad);
}
seen.add(nums[third]);
}
}
}
return [...found.values()];
}Optimal: Sort And Two Pointers
R3 Optimal: sort, fix two, squeeze, skip the repeats
sort nums
quads = empty list
for each first, up to the fourth from the end:
same as the one before? skip
for each second after first, up to the third from the end:
second > first + 1 and same as the one before? skip
left = second + 1; right = last
while left < right:
sum = the four numbers (in long)
too small: left up; too big: right down
equal: add the quad, left up, right down
skip equal numbers: left up, right down
return quads
Derivation: the set exists only to throw repeats away, and seen costs memory. Sort the row: repeats sit side by side (skip “same as my neighbour”), and the squeeze from Two Sum II needs no memory.
Why second > first + 1: the first second right after first may hold the same number ([2, 2, 2, 2] needs two 2s). Only a LATER equal second is a repeat.
Dry run on example 1, sorted [-2, -1, 0, 0, 1, 2], target 0: first -2 finds [-2, -1, 1, 2] and [-2, 0, 0, 2], then the second 0 as second: skip. First -1 finds [-1, 0, 0, 1], second 0 again: skip. 7 looks, 3 quads.
Example 2, [2, 2, 2, 2, 2], target 8: one look finds [2, 2, 2, 2]; the next second (a 2, not first + 1) skips; the next first (a 2) skips.
Complexity: O(n³) time, O(1) extra space apart from the answer.
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> quads = new ArrayList<>();
for (int first = 0; first < nums.length - 3; first++) {
// same first number as last time: its quads are already found
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
for (int second = first + 1; second < nums.length - 2; second++) {
// second may equal first once (2, 2, ...); after that an equal second is a repeat
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
int left = second + 1;
int right = nums.length - 1;
while (left < right) {
// long: four big ints can go past the int limit (overflow)
long sum = (long) nums[first] + nums[second]
+ nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
quads.add(Arrays.asList(
nums[first], nums[second], nums[left], nums[right]));
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
}
return quads;
}
}class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> quads;
for (int first = 0; first + 3 < nums.size(); first++) {
// same first number as last time: its quads are already found
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
for (int second = first + 1; second + 2 < nums.size(); second++) {
// second may equal first once (2, 2, ...); after that an equal second is a repeat
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
int left = second + 1;
int right = nums.size() - 1;
while (left < right) {
// long: four big ints can go past the int limit (overflow)
long long sum = (long long) nums[first] + nums[second]
+ nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
quads.push_back({nums[first], nums[second],
nums[left], nums[right]});
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
}
return quads;
}
};
void print(const vector<vector<int>>& quads) {
cout << "[";
for (size_t q = 0; q < quads.size(); q++) {
cout << (q ? ", [" : "[") << quads[q][0] << ", " << quads[q][1] << ", " << quads[q][2] << ", " << quads[q][3] << "]";
}
cout << "]" << endl;
}def fourSum(nums, target):
nums.sort()
quads = []
for first in range(len(nums) - 3):
if first > 0 and nums[first] == nums[first - 1]:
continue
for second in range(first + 1, len(nums) - 2):
if second > first + 1 and nums[second] == nums[second - 1]:
continue
left = second + 1
right = len(nums) - 1
while left < right:
sum = nums[first] + nums[second] + nums[left] + nums[right]
if sum < target:
left += 1
elif sum > target:
right -= 1
else:
quads.append([nums[first], nums[second], nums[left], nums[right]])
left += 1
right -= 1
# skip repeats so the same group is not added twice
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return quadsfunction fourSum(nums, target) {
nums.sort((a, b) => a - b);
const quads = [];
for (let first = 0; first < nums.length - 3; first++) {
// same first number as last time: its quads are already found
if (first > 0 && nums[first] === nums[first - 1]) {
continue;
}
for (let second = first + 1; second < nums.length - 2; second++) {
// second may equal first once (2, 2, ...); after that an equal second is a repeat
if (second > first + 1 && nums[second] === nums[second - 1]) {
continue;
}
let left = second + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[first] + nums[second] + nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
quads.push([nums[first], nums[second], nums[left], nums[right]]);
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] === nums[left - 1]) {
left++;
}
while (left < right && nums[right] === nums[right + 1]) {
right--;
}
}
}
}
}
return quads;
}Follow-up: K Sum
Follow-up: k-Sum (any k)
fourSum(nums, target):
sort nums
return kSum(nums, target, start = 0, k = 4)
kSum(nums, target, start, k):
groups = empty list
if k == 2:
squeeze left = start, right = last (skip repeats after a hit)
return the pairs
for each pick from start, leaving room for k - 1 more:
pick > start and same as the one before? skip
for each rest in kSum(nums, target - nums[pick], pick + 1, k - 1):
add [nums[pick]] + rest to groups
return groups
Derivation: 3Sum fixed one number and ran Two Sum; 4Sum fixed two. Every level does the same job: fix one number, then solve the same problem with one number fewer. So write that job once and let it call itself until two numbers are left.
pick > start is the same rule as second > first + 1: the first pick at a level may equal the number before it.
No backtracking list to undo: each call returns finished groups and the caller puts its own number in front.
Complexity: O(n^(k-1)) time (k - 2 fixed numbers, then an O(n) squeeze), O(k) for the calls. k = 4 gives O(n³).
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
return kSum(nums, target, 0, 4);
}
private List<List<Integer>> kSum(int[] nums, long target,
int start, int k) {
List<List<Integer>> groups = new ArrayList<>();
// two numbers left: the Two Sum II squeeze
if (k == 2) {
int left = start;
int right = nums.length - 1;
while (left < right) {
long sum = (long) nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
List<Integer> pair = new ArrayList<>();
pair.add(nums[left]);
pair.add(nums[right]);
groups.add(pair);
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
return groups;
}
for (int pick = start; pick < nums.length - k + 1; pick++) {
// same rule as second > first + 1: the first pick may equal the number before it
if (pick > start && nums[pick] == nums[pick - 1]) {
continue;
}
for (List<Integer> rest
: kSum(nums, target - nums[pick], pick + 1, k - 1)) {
rest.add(0, nums[pick]);
groups.add(rest);
}
}
return groups;
}
}class Solution {
public:
vector<vector<int>> kSum(vector<int>& nums, long long target, int start, int k) {
vector<vector<int>> groups;
// two numbers left: the Two Sum II squeeze
if (k == 2) {
int left = start;
int right = nums.size() - 1;
while (left < right) {
long long sum = (long long) nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
groups.push_back({nums[left], nums[right]});
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
return groups;
}
for (int pick = start; pick + k <= nums.size(); pick++) {
// same rule as second > first + 1: the first pick may equal the number before it
if (pick > start && nums[pick] == nums[pick - 1]) {
continue;
}
for (vector<int> rest : kSum(nums, target - nums[pick], pick + 1, k - 1)) {
rest.insert(rest.begin(), nums[pick]);
groups.push_back(rest);
}
}
return groups;
}
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
return kSum(nums, target, 0, 4);
}
};
void print(const vector<vector<int>>& quads) {
cout << "[";
for (size_t q = 0; q < quads.size(); q++) {
cout << (q ? ", [" : "[") << quads[q][0] << ", " << quads[q][1] << ", " << quads[q][2] << ", " << quads[q][3] << "]";
}
cout << "]" << endl;
}def fourSum(nums, target):
nums.sort()
return kSum(nums, target, 0, 4)
def kSum(nums, target, start, k):
groups = []
if k == 2:
left = start
right = len(nums) - 1
while left < right:
sum = nums[left] + nums[right]
if sum < target:
left += 1
elif sum > target:
right -= 1
else:
groups.append([nums[left], nums[right]])
left += 1
right -= 1
# skip repeats so the same group is not added twice
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return groups
for pick in range(start, len(nums) - k + 1):
if pick > start and nums[pick] == nums[pick - 1]:
continue
for rest in kSum(nums, target - nums[pick], pick + 1, k - 1):
groups.append([nums[pick]] + rest)
return groupsfunction fourSum(nums, target) {
nums.sort((a, b) => a - b);
return kSum(nums, target, 0, 4);
}
function kSum(nums, target, start, k) {
const groups = [];
// two numbers left: the Two Sum II squeeze
if (k === 2) {
let left = start;
let right = nums.length - 1;
while (left < right) {
const sum = nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
groups.push([nums[left], nums[right]]);
left++;
right--;
// skip repeats so the same group is not added twice
while (left < right && nums[left] === nums[left - 1]) {
left++;
}
while (left < right && nums[right] === nums[right + 1]) {
right--;
}
}
}
return groups;
}
for (let pick = start; pick < nums.length - k + 1; pick++) {
// same rule as second > first + 1: the first pick may equal the number before it
if (pick > start && nums[pick] === nums[pick - 1]) {
continue;
}
for (const rest of kSum(nums, target - nums[pick], pick + 1, k - 1)) {
groups.push([nums[pick], ...rest]);
}
}
return groups;
}