Guide contents

Lesson 33 of 250

18. 4Sum

NeetCode: 4Sum · LeetCode: 18. 4Sum · Difficulty: Medium

Given an array nums of n integers and an integer target, return all unique quadruplets [a, b, c, d] (values, not indices) with a + b + c + d == target. The result must not contain duplicate quadruplets, and may be returned in any order. Sums can exceed the int range, so the code adds in long.

Example

Text
Input:  nums = [1, 0, -1, 0, -2, 2], target = 0    Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Input:  nums = [2, 2, 2, 2, 2], target = 8         Output: [[2, 2, 2, 2]]

Brute force: four nested loops plus a set

Try every choice of four distinct indices i < j < k < l. When the sum matches, sort the four values and insert them into a TreeSet<List<Integer>> with a comparator that orders lists element by element; the set removes duplicate quadruplets and gives a deterministic order.

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

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        // Lists compare by contents; this comparator orders them lexicographically.
        TreeSet<List<Integer>> found = new TreeSet<>((a, b) -> {
            for (int i = 0; i < 4; i++) {
                int c = Integer.compare(a.get(i), b.get(i));
                if (c != 0) {
                    return c;
                }
            }
            return 0;
        });
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    for (int l = k + 1; l < n; l++) {
                        long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];
                        if (sum == target) {
                            int[] q = {nums[i], nums[j], nums[k], nums[l]};
                            Arrays.sort(q);
                            found.add(Arrays.asList(q[0], q[1], q[2], q[3]));
                        }
                    }
                }
            }
        }
        return new ArrayList<>(found);
    }
}

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0));
        System.out.println(s.fourSum(new int[]{2, 2, 2, 2, 2}, 8));
        System.out.println(s.fourSum(new int[]{1, 2, 3}, 6));
        System.out.println(s.fourSum(new int[]{1_000_000_000, 1_000_000_000, 1_000_000_000, 1_000_000_000}, -294_967_296));
    }
}
Output
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
[[2, 2, 2, 2]]
[]
[]

Time: O(n^4) for the loops (plus O(log q) per hit for the tree set, where q is the number of distinct quadruplets). Space: O(q) for the set.

Optimal: sort, fix two numbers, sweep with two pointers

This extends 3Sum with one more outer loop. Sort the array first. Fix the first two numbers nums[i] and nums[j], then the remaining two must sum to target - nums[i] - nums[j]. Because the rest of the array is sorted, a left pointer l = j + 1 and a right pointer r = n - 1 find that pair in one pass: if the sum is too small move l right, if too big move r left.

Duplicates are avoided by skipping equal values instead of using a set: skip nums[i] if it equals the previous value at the same loop level, do the same for j (only when j > i + 1), and after recording a match advance l and r past equal neighbours. All sums are computed in long: (long) a[i] + a[j] + ... widens the first operand, so the whole addition is done in long. Adding four int values first and widening afterwards would wrap before the cast.

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

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int[] a = nums.clone();
        Arrays.sort(a);
        int n = a.length;
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && a[i] == a[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && a[j] == a[j - 1]) {
                    continue;
                }
                int l = j + 1, r = n - 1;
                while (l < r) {
                    long sum = (long) a[i] + a[j] + a[l] + a[r];
                    if (sum < target) {
                        l++;
                    } else if (sum > target) {
                        r--;
                    } else {
                        res.add(Arrays.asList(a[i], a[j], a[l], a[r]));
                        l++;
                        r--;
                        while (l < r && a[l] == a[l - 1]) {
                            l++;
                        }
                        while (l < r && a[r] == a[r + 1]) {
                            r--;
                        }
                    }
                }
            }
        }
        return res;
    }
}

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0));
        System.out.println(s.fourSum(new int[]{2, 2, 2, 2, 2}, 8));
        System.out.println(s.fourSum(new int[]{1, 2, 3}, 6));
        System.out.println(s.fourSum(new int[]{1_000_000_000, 1_000_000_000, 1_000_000_000, 1_000_000_000}, -294_967_296));
    }
}
Output
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
[[2, 2, 2, 2]]
[]
[]

Time: O(n^3) (sorting is O(n log n), two nested loops times an O(n) sweep). Space: O(1) extra besides the sorted copy (nums.clone(), so the input is not changed) and the output.

The last test uses four values of 1_000_000_000. Their true sum, 4_000_000_000, does not fit in int, and the target would match only after an int overflow wrap, so the correct answer is no match.