4Sum solution explained
4Sum is solved by sorting the array, fixing the first two values with two nested loops, and finding the last two with a pair of pointers that move inward from both ends of the remaining range. Skipping repeated values at each of the four positions keeps every quadruplet unique. That is O(n³) time and O(1) extra space besides the output and the sort, down from O(n⁴) for checking every group of four.
By Evin JohnPublished 7 min read
The problem in our words
Given an integer array and a target, find all groups of four values, taken from four different positions, whose sum equals the target. Two groups that contain the same values count as one, whatever positions they came from. Return the groups in any order. The array can contain repeats and negative numbers.
| Array | Target | Unique quadruplets |
|---|---|---|
| [3, -1, 0, 2, -2, 1, -3] | 0 | [-3, -2, 2, 3], [-3, -1, 1, 3], [-3, 0, 1, 2], [-2, -1, 0, 3], [-2, -1, 1, 2] |
| [3, 3, 3, 3, 3, 3] | 12 | [3, 3, 3, 3] once, despite 15 ways to pick four positions |
| [5, -5, 5, -5] | 0 | [-5, -5, 5, 5] |
| [4, 1, -2, 3, 0, -1] | 5 | [-2, 0, 3, 4] |
| [1, 2, 3] | 6 | None: fewer than four values |
What interviewers check
4Sum is usually asked after Two Sum or 3Sum to see whether you can generalize. The two-pointer step is familiar by then; the hard parts are duplicate handling at four levels and doing it without a set of results. Interviewers also listen for overflow awareness in languages with fixed-width integers, since four large values can exceed a 32-bit sum.
Follow-ups
- Write it for any k. Recursion that fixes one value per level and bottoms out at two pointers. Shown below in JavaScript.
- Count the quadruplets from four separate arrays, one value from each. Store every pairwise sum of the first two arrays in a hash map, then look up the negated sums of the other two. O(n²).
- Return positions rather than values, or allow reuse. Each changes the duplicate rules; agree on them first.
- Prune harder. After sorting, if the smallest possible sum from the current start already exceeds the target, stop; if the largest possible sum is below it, skip ahead.
Brute force
Try every combination of four positions. Sorting first means every quadruplet comes out in non-decreasing order, so a set of tuples removes duplicates. This takes O(n⁴) time, fine for tiny inputs and as a reference when testing a faster version, but it is not an answer to stop at.
from itertools import combinations
def four_sum_brute(nums, target):
found = set()
for quad in combinations(sorted(nums), 4): # sorted, so each tuple is canonical
if sum(quad) == target:
found.add(quad)
return [list(q) for q in found]Sort, two loops, two pointers
Sort the array. Loop a over the first value and b over the second, with b always after a. For each pair, the last two values must add up to target minus both. Since the remaining range is sorted, put lo just after b and hi at the end. If the four-value sum is too small, move lo right; if too large, move hi left; if equal, record it and move both inward. Duplicates are handled by skipping a value at each level when it equals the previous value at that same level.
def four_sum(nums, target):
nums = sorted(nums)
n = len(nums)
result = []
for a in range(n - 3):
if a > 0 and nums[a] == nums[a - 1]:
continue # same first value, same results
for b in range(a + 1, n - 2):
if b > a + 1 and nums[b] == nums[b - 1]:
continue # same second value for this a
lo, hi = b + 1, n - 1
while lo < hi:
total = nums[a] + nums[b] + nums[lo] + nums[hi]
if total < target:
lo += 1
elif total > target:
hi -= 1
else:
result.append([nums[a], nums[b], nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip repeats of the third value
hi -= 1
return resultNote the conditions b > a + 1 and a > 0 in the skips. They allow the same value to be used at two levels, as in [-5, -5, 5, 5], while still preventing the same value from being tried twice at one level. After a match, skipping repeats on the lo side is enough, because hi moves too and the next match must use a different lo value.
A k-sum version in JavaScript
The same reduction works for any k. A recursive helper fixes one value, then asks for a (k - 1)-sum on the rest of the array with a smaller goal. When k reaches 2, it runs the two-pointer scan. This version skips a repeated lo value during the scan itself instead of after a match. Writing it once and calling it with k = 4 shows the interviewer you see the pattern rather than the specific problem.
function fourSum(nums, target) {
const sorted = nums.slice().sort((x, y) => x - y);
// k-sum on sorted[start..]: peel one value per level, two pointers at k = 2.
function kSum(start, k, goal) {
const out = [];
if (k === 2) {
let lo = start;
let hi = sorted.length - 1;
while (lo < hi) {
const s = sorted[lo] + sorted[hi];
if (s < goal || (lo > start && sorted[lo] === sorted[lo - 1])) lo++;
else if (s > goal) hi--;
else out.push([sorted[lo++], sorted[hi--]]);
}
return out;
}
for (let i = start; i <= sorted.length - k; i++) {
if (i > start && sorted[i] === sorted[i - 1]) continue;
for (const rest of kSum(i + 1, k - 1, goal - sorted[i])) {
out.push([sorted[i], ...rest]);
}
}
return out;
}
return kSum(0, 4, target);
}The comparator (x, y) => x - y matters. JavaScript's default sort compares values as strings, so without it, -2 and 10 would be sorted wrongly. JavaScript numbers are doubles, so sums of values up to around 10^9 stay exact; in C++ or Java, compute the sum in a 64-bit type.
Complexity
| Approach | Time | Extra space besides the output | Duplicates handled by |
|---|---|---|---|
| All groups of four | O(n⁴) | Set of results | A set |
| Sort, two loops, two pointers | O(n³) | O(1) plus the sort | Skipping equal neighbours |
| Recursive k-sum | O(n^(k-1)) | O(k) recursion | Skipping equal neighbours |
| Pair sums in a hash map | O(n²) average | O(n²) | Hard to deduplicate by value; better for counting |
Edge cases
- Fewer than four values: return an empty list.
- One value repeated many times, which should yield at most one quadruplet.
- A quadruplet that uses the same value twice, such as two copies of -5.
- Large values whose sum overflows 32-bit integers in C++ or Java.
- No match at all.
Mistakes
- At the second level, testing b > 0 instead of b > a + 1, which skips a valid second copy of the first value and loses answers like [-5, -5, 5, 5].
- Forgetting to move a pointer after a match, which loops forever.
- Adding every result to a set and calling the solution O(n³) without mentioning the hashing cost or the extra memory.
- Using JavaScript's default sort on numbers.
- Summing four ints in a 32-bit type.
Talking through it
Fictional example
- Candidate
- I'll sort first. Then I fix the first two values with two loops, and for the last two I use pointers from both ends of what's left, like sorted Two Sum.
- Candidate
- For uniqueness, at each level I skip a value equal to the one before it at that level. That keeps the same value usable at different levels, which I need for answers like minus five, minus five, five, five.
- Candidate
- Two loops times a linear scan is n cubed. The sort is n log n, so it doesn't change the total.
- Interviewer
- What about any k?
- Candidate
- A recursive function that fixes one value and asks for k minus one on the rest, with two pointers at the bottom. That's n to the k minus one.
Related problems
Two Sum covers the hash map version of the pair search that sits at the bottom of this one. Subarray Sum Equals K uses a hash map of running totals instead. Next Permutation and Sort Colors are further pointer problems on arrays, and Rotate Array works on the whole array in place.
Practicing it with Natively
Duplicate handling is where 4Sum attempts usually break. Natively can read the problem from a screenshot on Mac or Windows and suggest the sorted two-pointer approach and code, which you can run against your own version to see which quadruplets differ. If you practice with someone over a call, Natively transcribes both sides so you can review how you explained the skip rules. More on AI help for coding interviews.
Questions people ask
What is the time complexity of 4Sum?
O(n³) with sorting, two nested loops for the first two values and two pointers for the last two. Checking every group of four is O(n⁴).
How do you avoid duplicate quadruplets in 4Sum?
Sort the array and, at each of the four positions, skip a value that equals the previous value at the same level. That keeps one branch per distinct value without needing a set of results.
How do you solve k-sum in general?
Recursively: fix one value, solve (k - 1)-sum on the rest with a reduced target, and use two pointers when k reaches 2. It runs in O(n^(k-1)) time on a sorted array.
Can 4Sum overflow?
Yes, in languages with 32-bit integers. Four values near the limit can exceed it, so compute the sum in a 64-bit type.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
