15% off all plans & roadmaps Use code
See plans4Sum
- LeetCode 18
- Medium
- Two Pointers
- Converging (Sorted Array Target Sum)
Updated
TL;DR: Sort the array, then try every pair of starting indices (i, j) and scan the rest of the array with converging two pointers. The sorted order lets each scan discard one candidate per step, which brings the work from O(n^4) down to O(n^3).
Problem
You are given an integer array nums of length n. Return every unique quadruplet [nums[a], nums[b], nums[c], nums[d]] that meets all three rules below.
0 <= a, b, c, d < na,b,c, anddare distinct indices.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer 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
Constraints that matter
- n up to 200 means a plain scan of all index quadruples does about 6.5 * 10^7 checks, which is C(200, 4). Fixing two indices and scanning the rest with pointers does about 4 * 10^6 steps, so a cubic method fits easily.
- Values up to 10^9 in size mean one sum can reach 4 * 10^9, which overflows a 32-bit int. The sum needs a 64-bit type in Java, C++ and C#.
- Answers must be unique by value, not by index. Sorting puts equal values next to each other, so skipping a repeat costs one comparison.
- n can be 1, so the code must handle arrays with fewer than four values and return an empty list.
Hints
Hint 1
The answer is a set of value combinations, not index combinations, so duplicates are the main trap.
Hint 2
The naive solution checks every set of four distinct indices.
Solution
Intuition
The answer is a set of value combinations, not index combinations, so duplicates are the main trap. Sorting handles that. Equal values end up next to each other, so one comparison tells you to skip a repeat.
Picture a sorted row of price tags with one hand at each end. Each move drops one tag the total cannot use, and the hands close in until they meet.
This problem uses the two pointers pattern in its converging form, applied in a chain. Fixing one value turns 4Sum into 3Sum. Fixing a second value turns it into 2Sum, and 2Sum on a sorted range is solved by a left pointer and a right pointer that close in from both ends.
The sum tells you which pointer to move. If the sum is below the target, the left value is too small even when paired with the largest remaining value, so you can discard it. If the sum is above the target, the right value is too large even with the smallest remaining left value. Each move throws away one candidate that cannot be part of an answer.
Worked example
Input: nums = [2, 2, 2, 2, 2], target = 8 Output: [[2,2,2,2]] Explanation: Every value is 2, so any four of the five positions sum to 8. All five index choices produce the same quadruplet, so the answer keeps a single copy.
Approach 1: Brute force
The naive solution checks every set of four distinct indices. For each set that sums to the target, it sorts the four values and stores them in a set. The set collapses repeated answers into one entry.
The work depends only on the number of index sets, not on the values. The loops never use the sorted order, so this approach is correct but slow.
Steps
- Create an empty set to hold the answers.
- Loop over indices a < b < c < d so no index repeats.
- Compute the sum of the four values at those indices.
- If the sum equals target, sort the four values and add them to the set.
- Convert the set into a list and return it.
Dry run
On [2, 2, 2, 2, 2] with target 8 there are C(5, 4) = 5 index sets: (0,1,2,3), (0,1,2,4), (0,1,3,4), (0,2,3,4) and (1,2,3,4). Each set sums to 8, and each sorted tuple is (2, 2, 2, 2). The set keeps the first tuple and ignores the other four. The output is [[2,2,2,2]], which matches the example.
Complexity
| Time | O(n^4) |
|---|---|
| Space | O(u), where u is the number of unique quadruplets |
Here n is the array length. Four nested loops with a < b < c < d run C(n, 4) times, which is about n^4 / 24, so the time is O(n^4). Each sum and each sort of four values takes constant work. The set holds one entry per unique answer, so the extra space is O(u).
PythonTested in our runner
from typing import List, Optional
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
found = set()
for a in range(n):
for b in range(a + 1, n):
for c in range(b + 1, n):
for d in range(c + 1, n):
if nums[a] + nums[b] + nums[c] + nums[d] == target:
# Sorting the four values makes the key independent of index order.
found.add(tuple(sorted((nums[a], nums[b], nums[c], nums[d]))))
# Sort the unique quadruplets so the output order is deterministic.
return [list(quad) for quad in sorted(found)]
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] fourSum(int[] nums, int target) {
int n = nums.length;
Set<List<Integer>> found = new HashSet<>();
for (int a = 0; a < n; a++) {
for (int b = a + 1; b < n; b++) {
for (int c = b + 1; c < n; c++) {
for (int d = c + 1; d < n; d++) {
// Use long so the sum of four values cannot overflow.
long sum = (long) nums[a] + nums[b] + nums[c] + nums[d];
if (sum == target) {
int[] quad = {nums[a], nums[b], nums[c], nums[d]};
Arrays.sort(quad);
List<Integer> key = new ArrayList<>();
for (int v : quad) key.add(v);
found.add(key);
}
}
}
}
}
int[][] result = new int[found.size()][];
int idx = 0;
for (List<Integer> key : found) {
int[] row = new int[4];
for (int t = 0; t < 4; t++) row[t] = key.get(t);
result[idx++] = row;
}
// Sort lexicographically so the output order is deterministic.
Arrays.sort(result, (x, y) -> {
for (int t = 0; t < 4; t++) {
if (x[t] != y[t]) return Integer.compare(x[t], y[t]);
}
return 0;
});
return result;
}
}C++Tested in our runner
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
set<vector<int>> found;
for (int a = 0; a < n; a++)
for (int b = a + 1; b < n; b++)
for (int c = b + 1; c < n; c++)
for (int d = c + 1; d < n; d++) {
// long long keeps the sum from overflowing.
long long sum = (long long)nums[a] + nums[b] + nums[c] + nums[d];
if (sum == target) {
vector<int> quad = {nums[a], nums[b], nums[c], nums[d]};
sort(quad.begin(), quad.end());
found.insert(quad);
}
}
return vector<vector<int>>(found.begin(), found.end());
}
};JavaScriptTested in our runner
var fourSum = function(nums, target) {
const n = nums.length;
// Set de-duplicates quadruplets; keys are sorted values joined by commas
const found = new Set();
for (let a = 0; a < n; a++) {
for (let b = a + 1; b < n; b++) {
for (let c = b + 1; c < n; c++) {
for (let d = c + 1; d < n; d++) {
if (nums[a] + nums[b] + nums[c] + nums[d] === target) {
const quad = [nums[a], nums[b], nums[c], nums[d]].sort((x, y) => x - y);
found.add(quad.join(","));
}
}
}
}
}
// Convert keys back to numbers and sort the result lexicographically
return [...found]
.map(key => key.split(",").map(Number))
.sort((p, q) => p[0] - q[0] || p[1] - q[1] || p[2] - q[2] || p[3] - q[3]);
};GoTested in our runner
import "sort"
func fourSum(nums []int, target int) [][]int {
n := len(nums)
seen := map[[4]int]bool{}
result := [][]int{}
for a := 0; a < n; a++ {
for b := a + 1; b < n; b++ {
for c := b + 1; c < n; c++ {
for d := c + 1; d < n; d++ {
if nums[a]+nums[b]+nums[c]+nums[d] == target {
quad := []int{nums[a], nums[b], nums[c], nums[d]}
sort.Ints(quad)
key := [4]int{quad[0], quad[1], quad[2], quad[3]}
if !seen[key] {
seen[key] = true
result = append(result, quad)
}
}
}
}
}
}
// Sort the unique quadruplets lexicographically to match the expected order
sort.Slice(result, func(i, j int) bool {
for k := 0; k < 4; k++ {
if result[i][k] != result[j][k] {
return result[i][k] < result[j][k]
}
}
return false
})
return result
}C#Tested in our runner
using System;
using System.Collections.Generic;
public class Solution {
public int[][] fourSum(int[] nums, int target) {
int n = nums.Length;
var seen = new HashSet<string>();
var result = new List<int[]>();
for (int a = 0; a < n; a++)
for (int b = a + 1; b < n; b++)
for (int c = b + 1; c < n; c++)
for (int d = c + 1; d < n; d++) {
long sum = (long)nums[a] + nums[b] + nums[c] + nums[d];
if (sum == target) {
int[] quad = { nums[a], nums[b], nums[c], nums[d] };
Array.Sort(quad);
string key = string.Join(",", quad);
if (seen.Add(key)) result.Add(quad);
}
}
// Sort quadruplets lexicographically to match the expected order
result.Sort((x, y) => {
for (int i = 0; i < 4; i++) {
if (x[i] != y[i]) return x[i].CompareTo(y[i]);
}
return 0;
});
return result.ToArray();
}
}The Converging (Sorted Array Target Sum) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Converging (Sorted Array Target Sum)
Part of Two Pointers
Approach 2: Sort, fix two, then converging two pointersOptimalConverging (Sorted Array Target Sum)
What's slow: the brute force checks each index set on its own, so it repeats the same pair sums over and over. Four nested loops cost n^4 work, and every match pays for a sort.
The insight that fixes it: after sorting, fix the first two indices and treat the last two as a 2Sum problem on the sorted tail. Converging pointers solve that in one linear scan, so the last two loops collapse into one pass.
Duplicates are handled by value. Skip a first or second index whose value repeats the one before it. After a match, skip every copy of the pointer values before moving on.
Why it is correct. The range between left and right always holds every candidate that could still complete the quadruplet for the fixed first two values. If the sum is below target, nums[left] paired with any value up to right is at most the current sum, so it can be dropped. The same argument drops right when the sum is above target, and skipping repeated values only skips identical value sets already tried.
Steps
- Sort
numsin ascending order. Return an empty list if n is less than 4. - For each start index i, skip it if nums[i] equals nums[i - 1].
- For each j after i, skip it if j > i + 1 and nums[j] equals nums[j - 1].
- Set left to j + 1 and right to n - 1. Compute the sum of the four values.
- If the sum equals target, record the quadruplet, then move left and right past every copy of their current values.
- If the sum is below target, move left one step right. If it is above target, move right one step left.
- Return the recorded quadruplets.
Dry run
Start with the sorted array [2, 2, 2, 2, 2] and target 8. The table tracks every change in order.
| Step | i | j | left | right | sum | Action | Answers |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 2 | 4 | 8 | sum equals target, record it | [[2,2,2,2]] |
| 2 | 0 | 1 | 4 | 4 | n/a | skip equal values, left stops at right | [[2,2,2,2]] |
| 3 | 0 | 1 | 4 | 4 | n/a | left is not less than right, scan ends | [[2,2,2,2]] |
| 4 | 0 | 2 | n/a | n/a | n/a | nums[2] equals nums[1] and 2 > 0 + 1, skip | [[2,2,2,2]] |
| 5 | 1 | n/a | n/a | n/a | n/a | nums[1] equals nums[0], skip | [[2,2,2,2]] |
| 6 | n/a | n/a | n/a | n/a | n/a | loops end, return the list | [[2,2,2,2]] |
The output is [[2,2,2,2]], which matches the example.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(1) extra, apart from the output and the sort's own memory |
Here n is the array length. Sorting costs O(n log n), which the rest of the work absorbs. The pair loops visit at most about n^2 / 2 pairs (i, j). Each pointer scan moves at most n times, because the gap between left and right shrinks on every step. That gives O(n^2) * O(n) = O(n^3). The extra memory is a few integers, so the space is O(1) beyond the output.
PythonTested in our runner
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
if n < 4:
return result
for i in range(n - 3):
# Skip a first index whose value was already used.
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
# Skip a repeated second value, but never the first j after i.
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
left_val, right_val = nums[left], nums[right]
# Skip every copy of both pointer values.
while left < right and nums[left] == left_val:
left += 1
while left < right and nums[right] == right_val:
right -= 1
elif total < target:
left += 1
else:
right -= 1
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[][] fourSum(int[] nums, int target) {
int n = nums.length;
List<int[]> result = new ArrayList<>();
if (n < 4) return new int[0][];
Arrays.sort(nums);
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 left = j + 1, right = n - 1;
while (left < right) {
// long avoids overflow when four values are near 10^9.
long total = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (total == target) {
result.add(new int[] {nums[i], nums[j], nums[left], nums[right]});
int leftVal = nums[left], rightVal = nums[right];
while (left < right && nums[left] == leftVal) left++;
while (left < right && nums[right] == rightVal) right--;
} else if (total < target) {
left++;
} else {
right--;
}
}
}
}
return result.toArray(new int[0][]);
}
}C++Tested in our runner
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> result;
if (n < 4) return result;
sort(nums.begin(), nums.end());
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 left = j + 1, right = n - 1;
while (left < right) {
long long total = (long long)nums[i] + nums[j] + nums[left] + nums[right];
if (total == target) {
result.push_back({nums[i], nums[j], nums[left], nums[right]});
int leftVal = nums[left], rightVal = nums[right];
while (left < right && nums[left] == leftVal) left++;
while (left < right && nums[right] == rightVal) right--;
} else if (total < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
};JavaScriptTested in our runner
var fourSum = function(nums, target) {
nums.sort((x, y) => x - y);
const n = nums.length;
const result = [];
if (n < 4) return result;
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 total = nums[i] + nums[j] + nums[left] + nums[right];
if (total === target) {
result.push([nums[i], nums[j], nums[left], nums[right]]);
const leftVal = nums[left], rightVal = nums[right];
while (left < right && nums[left] === leftVal) left++;
while (left < right && nums[right] === rightVal) right--;
} else if (total < target) {
left++;
} else {
right--;
}
}
}
}
return result;
};GoTested in our runner
import "sort"
func fourSum(nums []int, target int) [][]int {
n := len(nums)
result := [][]int{}
if n < 4 {
return result
}
sort.Ints(nums)
for i := 0; i < n-3; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < n-2; j++ {
if j > i+1 && nums[j] == nums[j-1] {
continue
}
left, right := j+1, n-1
for left < right {
total := nums[i] + nums[j] + nums[left] + nums[right]
if total == target {
result = append(result, []int{nums[i], nums[j], nums[left], nums[right]})
leftVal, rightVal := nums[left], nums[right]
for left < right && nums[left] == leftVal {
left++
}
for left < right && nums[right] == rightVal {
right--
}
} else if total < target {
left++
} else {
right--
}
}
}
}
return result
}C#Tested in our runner
public class Solution {
public int[][] fourSum(int[] nums, int target) {
int n = nums.Length;
var result = new List<int[]>();
if (n < 4) return result.ToArray();
Array.Sort(nums);
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 left = j + 1, right = n - 1;
while (left < right) {
long total = (long)nums[i] + nums[j] + nums[left] + nums[right];
if (total == target) {
result.Add(new int[] { nums[i], nums[j], nums[left], nums[right] });
int leftVal = nums[left], rightVal = nums[right];
while (left < right && nums[left] == leftVal) left++;
while (left < right && nums[right] == rightVal) right--;
} else if (total < target) {
left++;
} else {
right--;
}
}
}
}
return result.ToArray();
}
}Common mistakes
if nums[j] == nums[j - 1]without thej > i + 1guard: on[2,2,2,2,2]with target 8 this skips j = 1 and loses[2,2,2,2]. Add the guard so the first j after i is never skipped.int total = nums[i] + nums[j] + nums[left] + nums[right]in Java, C++ or C#: values near 10^9 wrap around. Store the sum in a 64-bit type.- Recording a match without moving
leftandright: the pointers stay put and the same match repeats forever. Move both inward right after you record a quadruplet. - Moving
leftone step after a match without skipping copies: an input with two zeros can record[-1,0,0,1]twice. Skip every copy ofnums[left]andnums[right]before the next check. - Starting the pointers at
left = jinstead ofj + 1: the same index is used twice, which breaks the distinct-index rule and can build a quadruplet from only three numbers.
Edge cases
- n = 3, such as
[1, 1, 1]with target 3: fewer than four values means no quadruplet, so return an empty list. - All equal values,
[2,2,2,2,2]with target 8: return[[2,2,2,2]]once. With target 7 return an empty list. - Large values,
[-1000000000, -1000000000, 1000000000, 1000000000]with target 0: the sum is 0, so return that one quadruplet. The sum must not overflow. - Mixed signs with repeated zeros,
[1,0,-1,0,-2,2]with target 0: return the three unique quadruplets, with[-1,0,0,1]appearing once even though 0 occurs twice. - Repeated values used up to their count,
[1,1,1,1,2,2]with target 6: return[[1,1,2,2]]once, even though there are four 1s and two 2s. - Unreachable target,
[1,2,3,4]with target 100: no sum matches, so return an empty list.
Follow-ups interviewers ask
- What if you need k-Sum for any k?
- Fix one value, then solve (k-1)-Sum on the rest of the sorted array, skipping duplicates at each level. The base case is 2Sum with converging pointers, which takes O(n) on sorted input. The total is O(n^(k-1)) for k at least 3, so 4Sum comes out to O(n^3).
- Can you avoid changing the input array?
- Copy the array first and sort the copy. That costs O(n) extra space and leaves the caller's array untouched. The O(n^3) time bound stays the same.
- Can 4Sum be solved faster than O(n^3)?
- I do not know a general method that beats O(n^3) for arbitrary input, and interviews expect this bound. Say that the fix-two-then-scan reduction is the standard answer, then explain why it fits n up to 200.
4Sum FAQ
What is the time complexity of 4Sum?
The sorted two-pointer solution runs in O(n^3) time, where n is the array length. Sorting adds O(n log n), which the cubic scan absorbs. The brute force over all index sets runs in O(n^4).
Why use two pointers for 4Sum?
Once two values are fixed, the last two must sum to a fixed remainder on a sorted range. Two pointers from both ends find every such pair in linear time, because each move discards a candidate that cannot work.
Can 4Sum be solved in O(1) extra space?
The search itself needs only a few integers, so the extra space is O(1) apart from the sort. The sort's internal memory depends on the language, from O(log n) stack in an in-place quicksort to O(n) in Python's Timsort. The output list is not counted.
Why does 4Sum need duplicate skipping?
The answer asks for unique value combinations, and repeated values would produce the same list many times. Skipping a repeated first index, second index or pointer value keeps only the first copy of each group.
Is 4Sum the same as 3Sum with one more loop?
Yes in structure: each extra fixed value adds one loop around the 2Sum scan. This solution fixes two values, so it has two loops around one pointer scan.
Asked at
See which companies ask this — Pro
Related problems
- 3Sum · same technique: Converging (Sorted Array Target Sum)
- Container With Most Water · same technique: Converging (Sorted Array Target Sum)
- Two Sum II - Input Array Is Sorted · same technique: Converging (Sorted Array Target Sum)
- Boats to Save People · same technique: Converging (Sorted Array Target Sum)
- 3Sum Closest · same technique: Converging (Sorted Array Target Sum)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers