4Sum (LeetCode 18): Solution and Explanation

Medium
Array
Two Pointers
Sorting

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Sort nums and prepare an empty result list.
  2. Loop i from 0 to n - 4, skipping i when nums[i] == nums[i - 1] so the first value is never repeated.
  3. Inside, loop j from i + 1 to n - 3, skipping j when j > i + 1 and nums[j] == nums[j - 1].
  4. Set l = j + 1 and r = n - 1, and while l < r compute the sum of the four values.
  5. If the sum is below the target, move l right; if above, move r left.
  6. On a match, record the quadruplet, move l right, 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
  1. Sorting gives [-2, -1, 0, 0, 1, 2].
  2. With i = 0 (-2) and j = 1 (-1), the pointers start at 0 and 2. Sums of -1 move l right twice until -2 - 1 + 1 + 2 = 0, recording [-2, -1, 1, 2].
  3. 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 moves r left, and the pointers meet.
  4. j = 3 holds another 0, the same as nums[2], so it is skipped.
  5. With i = 1 (-1) and j = 2 (0), the first sum is 1, so r moves left, then -1 + 0 + 0 + 1 = 0 records [-1, 0, 0, 1].
  6. 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 res

Time and space complexity

Time

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.

Space

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 long or long long.
  • Skipping duplicates for j with j > 0 instead of j > i + 1. That skips the first j whenever nums[j] equals nums[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.