4 Sum

Given an array nums of n integers and a target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] with four different indices whose sum equals target. The answer must not contain the same quadruplet twice. This is LeetCode 18.

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]]

How to Think About It

Step 1: Build on 3Sum

3Sum sorts the array, fixes one number, and finds the other two with two pointers. 4Sum adds one more level: fix two numbers with two loops, then find the last two with two pointers.

Step 2: The inner search

After fixing indices i and j, put lo just after j and hi at the end:

  • sum too small: move lo right;
  • sum too big: move hi left;
  • equal: record the quadruplet and move both.

Step 3: Skip duplicates at every level

Sorting puts equal values together. Skip i if nums[i] equals the previous first value, skip j the same way, and after a match move lo past copies of the value just used. That prevents repeated quadruplets without needing a set.

Step 4: Watch for overflow

Values go up to 109, so four of them can exceed an int. Add them as a long.

Walkthrough

nums sorts to [-2, -1, 0, 0, 1, 2], target 0. The pairs (i, j) that lead to matches:

Fixed valuesNeed from the restPairs found by lo and hiQuadruplets
-2, -131 + 2[-2, -1, 1, 2]
-2, 020 + 2[-2, 0, 0, 2]
-2, 0 (second 0)skipped: same as the previous j
-1, 010 + 1[-1, 0, 0, 1]

Java Solution

fourSum sorts the array, fixes two values with i and j, and finds the other two with lo and hi:

  • Loop bounds: i < n - 3 and j < n - 2 leave room for the values still to be chosen, so a three-value array such as [1, 2, 3] returns [] without any search.
  • The sum is a long: four values near 109 add up to about 4 × 109, beyond int. The cast on nums[i] makes the whole addition run in long.
  • Repeats at both levels: j > i + 1 skips only repeats inside the current i, so [2, 2, 2, 2, 2] with target 8 still finds [2, 2, 2, 2], exactly once.

A common mistake is an int sum. For four copies of 1000000000 and target -294967296, the int total wraps around to -294967296, so that version reports the four values as a match. The long code correctly returns [].

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum {

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;                     // same first value: same quadruplets
            }
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;                 // same second value
                }
                int lo = j + 1;
                int hi = n - 1;
                while (lo < hi) {
                    long sum = (long) nums[i] + nums[j] + nums[lo] + nums[hi];   // can overflow int
                    if (sum < target) {
                        lo++;
                    } else if (sum > target) {
                        hi--;
                    } else {
                        result.add(List.of(nums[i], nums[j], nums[lo], nums[hi]));
                        lo++;
                        hi--;
                        while (lo < hi && nums[lo] == nums[lo - 1]) {
                            lo++;             // skip repeats of the third value
                        }
                    }
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(fourSum(new int[] {1, 0, -1, 0, -2, 2}, 0));
        // [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
        System.out.println(fourSum(new int[] {2, 2, 2, 2, 2}, 8));   // [[2, 2, 2, 2]]
    }
}

The original implementation, FourSum.java, is on GitHub.

Complexity

  • Time: O(n³). The sort is O(n log n); the two nested loops choose about n²/2 pairs (i, j), and for each pair the two-pointer pass over the rest of the array takes O(n) steps.
  • Space: O(1) besides the output and the sort. Only the indexes and the long sum are extra; the quadruplets in result are the answer, and the in-place sort uses only a small recursion stack.

For counting zero-sum tuples across four separate arrays, a hash map does better: see 4Sum II.