4Sum (LeetCode 18): Solution and Explanation
Given an integer array and a target, return every unique quadruplet of values at four different positions whose sum equals the target. The same set of four values must not appear twice in the output, even if it can be formed from different indices.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force checks every choice of four indices, which is O(n⁴), and then still has to remove duplicate quadruplets, for example by sorting each one and putting it in a set. With 200 numbers that is over a billion combinations, so you need to cut at least one level of looping.
If you have solved 3Sum, the pattern is familiar. Sort the array first. Then fix the first two numbers with nested loops, and for each pair, the problem becomes a Two Sum on the remaining sorted suffix: find two numbers that add up to target - nums[i] - nums[j]. In a sorted array, Two Sum is solved with two pointers that start at both ends. If the current sum is too small, move the left pointer right to increase it; if too large, move the right pointer left. That replaces the two innermost loops with a single linear scan, bringing the total to O(n³).
Sorting also makes duplicates easy to handle. Equal values sit next to each other, so at each of the two outer levels you skip an index whose value equals the previous one, because it would generate exactly the same quadruplets. After recording a match, advance the left pointer past any copies of the value just used. The right pointer does not need its own skip loop here: if the left value changed, the old right value can no longer produce the target, and the normal pointer logic will move it.
Approach: Sort, fix two, two pointers
- Sort
numsand prepare an empty result list. - Loop
ifrom 0 ton - 4, skippingiwhennums[i] == nums[i - 1]so the first value is never repeated. - Inside, loop
jfromi + 1ton - 3, skippingjwhenj > i + 1andnums[j] == nums[j - 1]. - Set
l = j + 1andr = n - 1, and whilel < rcompute the sum of the four values. - If the sum is below the target, move
lright; if above, moverleft. - On a match, record the quadruplet, move
lright, and keep moving it while it equals the previous value to skip duplicates. Return the result after all loops.
Step-by-step example
nums = [1, 0, -1, 0, -2, 2], target = 0
- Sorting gives [-2, -1, 0, 0, 1, 2].
- With
i = 0(-2) andj = 1(-1), the pointers start at 0 and 2. Sums of -1 movelright twice until -2 - 1 + 1 + 2 = 0, recording [-2, -1, 1, 2]. - With
j = 2(0), the pointers start at 0 and 2. The sum -2 + 0 + 0 + 2 = 0 records [-2, 0, 0, 2]. Then -2 + 0 + 1 + 2 = 1 movesrleft, and the pointers meet. j = 3holds another 0, the same asnums[2], so it is skipped.- With
i = 1(-1) andj = 2(0), the first sum is 1, sormoves left, then -1 + 0 + 0 + 1 = 0 records [-1, 0, 0, 1]. - No other pair produces a match, so the result is [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]].
Code: Python, Java, C++
1class Solution:
2 def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
3 res = []
4 nums.sort()
5 n = len(nums)
6
7 for i in range(n - 3):
8 if i > 0 and nums[i] == nums[i - 1]:
9 continue
10
11 for j in range(i + 1, n - 2):
12 if j > i + 1 and nums[j] == nums[j - 1]:
13 continue
14
15 l, r = j + 1, n - 1
16 while l < r:
17 total = nums[i] + nums[j] + nums[l] + nums[r]
18 if total < target:
19 l += 1
20 elif total > target:
21 r -= 1
22 else:
23 res.append([nums[i], nums[j], nums[l], nums[r]])
24 l += 1
25 while l < r and nums[l] == nums[l - 1]:
26 l += 1
27 return res1class Solution {
2 public List<List<Integer>> fourSum(int[] nums, int target) {
3 Arrays.sort(nums);
4 List<List<Integer>> res = new ArrayList<>();
5 int n = nums.length;
6
7 for (int i = 0; i < n - 3; i++) {
8 if (i > 0 && nums[i] == nums[i - 1]) continue;
9
10 for (int j = i + 1; j < n - 2; j++) {
11 if (j > i + 1 && nums[j] == nums[j - 1]) continue;
12
13 int l = j + 1, r = n - 1;
14 while (l < r) {
15 long sum = (long) nums[i] + nums[j] + nums[l] + nums[r];
16 if (sum < target) {
17 l++;
18 } else if (sum > target) {
19 r--;
20 } else {
21 res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
22 l++;
23 while (l < r && nums[l] == nums[l - 1]) {
24 l++;
25 }
26 }
27 }
28 }
29 }
30 return res;
31 }
32}1class Solution {
2public:
3 vector<vector<int>> fourSum(vector<int>& nums, int target) {
4 vector<vector<int>> res;
5 sort(nums.begin(), nums.end());
6 int n = nums.size();
7
8 for (int i = 0; i < n - 3; i++) {
9 if (i > 0 && nums[i] == nums[i - 1]) continue;
10
11 for (int j = i + 1; j < n - 2; j++) {
12 if (j > i + 1 && nums[j] == nums[j - 1]) continue;
13
14 int l = j + 1, r = n - 1;
15 while (l < r) {
16 long long sum = (long long) nums[i] + nums[j] + nums[l] + nums[r];
17 if (sum < target) {
18 l++;
19 } else if (sum > target) {
20 r--;
21 } else {
22 res.push_back({nums[i], nums[j], nums[l], nums[r]});
23 l++;
24 while (l < r && nums[l] == nums[l - 1]) {
25 l++;
26 }
27 }
28 }
29 }
30 }
31 return res;
32 }
33};Time and space complexity
O(n³)
Sorting is O(n log n). There are O(n²) choices of i and j, and for each the two pointers together scan at most n elements, giving O(n³) overall.
O(n)
Python's sort can use up to O(n) auxiliary memory; the pointer logic itself needs O(1). The output list is not counted.
Other approaches
Generalized k-Sum recursion (time O(n³), space O(n))
Write a recursive kSum that fixes one number and calls itself with k - 1 until k is 2, where it runs the two-pointer Two Sum. It solves 3Sum, 4Sum and beyond with one function, at O(n^(k-1)) time.
Pair sums in a hash map (time O(n²) average, O(n⁴) worst, space O(n²))
Precompute sums of all pairs and look for complementary pairs with disjoint indices. It can be faster on average for some inputs, but handling index overlap and duplicate quadruplets makes it much more complicated, and the worst case is no better.
Common mistakes
- Integer overflow in Java or C++. Four values up to 10^9 can exceed a 32-bit int, so compute the sum as a
longorlong long. - Skipping duplicates for
jwithj > 0instead ofj > i + 1. That skips the firstjwhenevernums[j]equalsnums[i], so an input like [0, 0, 0, 0] with target 0 loses its only answer. - Forgetting to move a pointer after recording a match, which loops forever on the same pair.
- Not sorting before using two pointers. The pointer moves only make sense when the suffix is in sorted order.
Frequently asked questions
What is the time complexity of 4Sum?
O(n³). Two nested loops choose the first two numbers, and a linear two-pointer scan finds the remaining pair for each choice.
How do you avoid duplicate quadruplets in 4Sum?
Sort the array so equal values are adjacent, skip repeated values for the first and second indices, and after each match advance the left pointer past repeats of the value just used.
How is 4Sum related to 3Sum and Two Sum?
Each adds one more fixed loop around the sorted two-pointer Two Sum. That pattern generalizes to k-Sum, costing O(n^(k-1)) time.