4Sum

Medium Arrays & Hashing Two Pointer Original on LeetCode

4Sum is a medium arrays & hashing problem solved with the two pointer pattern. The best approach, optimal (sort + two loops + two pointers), runs in O(n³) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (all quadruples + set) up.

Problem

You are given an integer array nums and an integer target. Return every distinct group of four values [a, b, c, d] taken from four different positions of nums such that a + b + c + d == target.

Two groups count as the same if they contain the same values (as a multiset), so each value group appears only once in the answer. The groups, and the values inside a group, may be returned in any order.

Examples

Example 1

Input
nums = [2, -1, 0, 3, -2, 1], target = 2
Output
[[-2, -1, 2, 3], [-2, 0, 1, 3], [-1, 0, 1, 2]]
Why
Each listed group of four values adds up to 2, and no other distinct group does.

Example 2

Input
nums = [5, 5, 5, 5, 5], target = 20
Output
[[5, 5, 5, 5]]
Why
Many index choices give the same values, but the quadruplet is reported once.

Example 3

Input
nums = [1, 2, 3], target = 6
Output
[]
Why
Fewer than four numbers, so no quadruplet exists.

Constraints

  • 1 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (all quadruples + set)O(n⁴)O(q)
Optimal (sort + two loops + two pointers)O(n³)O(1)

1Brute force (all quadruples + set)

TimeO(n⁴)There are about n⁴ / 24 index quadruples, each checked in O(1).
SpaceO(q)The set holds the q distinct answers.

Sort the array, try every choice of four indices i < j < k < l, and keep the value tuples whose sum equals the target in a set so repeated value groups are stored once.

  1. Sort nums so every tuple comes out in non-decreasing order.
  2. Four nested loops over i < j < k < l.
  3. If the 64-bit sum equals target, add the tuple to a set.
  4. Return the set as a list.
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        Set<List<Integer>> seen = new LinkedHashSet<>();
        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) seen.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
                    }
        return new ArrayList<>(seen);
    }
}

2Optimal (sort + two loops + two pointers)

TimeO(n³)n² choices of (i, j), each followed by an O(n) two-pointer sweep; sorting is O(n log n).
SpaceO(1)Only pointers besides the output (and the sort's own stack).

After sorting, fix the first value nums[i] and the second value nums[j]. The remaining pair must sum to target - nums[i] - nums[j], which two pointers find in one linear sweep of the rest of the array. Skipping equal neighbours at every level keeps each value group unique without a set.

  1. Sort nums.
  2. For each i, skip it if nums[i] == nums[i - 1].
  3. For each j > i, skip it if j > i + 1 and nums[j] == nums[j - 1].
  4. Set lo = j + 1, hi = n - 1 and compute the 64-bit sum.
  5. Sum too small → lo++; too big → hi--; equal → record, then move both pointers past equal values.
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> out = new ArrayList<>();
        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 lo = j + 1, hi = n - 1;
                while (lo < hi) {
                    long sum = (long) nums[i] + nums[j] + nums[lo] + nums[hi];
                    if (sum < target) lo++;
                    else if (sum > target) hi--;
                    else {
                        out.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi]));
                        while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                        while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                        lo++;
                        hi--;
                    }
                }
            }
        }
        return out;
    }
}

Edge cases to test

  • Fewer than four elements
  • All values equal (one answer, many index choices)
  • Sums that overflow a 32-bit int, like four values near 10^9
  • Negative target

Hints

Hint 1

Sorting makes duplicates sit next to each other, so they are easy to skip.

Hint 2

Fix the first two values with two loops. What is left is a two-sum on a sorted range.

Hint 3

Use two pointers for the last two values and do the arithmetic in 64-bit.

FAQ

What is the best time complexity for 4Sum?

Optimal (sort + two loops + two pointers) runs in O(n³) time and O(1) extra space. n² choices of (i, j), each followed by an O(n) two-pointer sweep; sorting is O(n log n).

Which pattern does 4Sum use?

It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.

Is there a brute force solution for 4Sum?

Yes. Brute force (all quadruples + set) takes O(n⁴) time and O(q) space. Sort the array, try every choice of four indices i < j < k < l, and keep the value tuples whose sum equals the target in a set so repeated value groups are stored once.

Which edge cases should I test for 4Sum?

Fewer than four elements; All values equal (one answer, many index choices); Sums that overflow a 32-bit int, like four values near 10^9; Negative target.