4Sum

Pattern: Two pointers

medium

Sort, fix the first two values with loops, and find the last two with pointers from both ends. Add in 64 bits, and skip repeats at every level.

The problem

You are given an array nums and a target. Return every distinct group of four values from four different positions that adds up to target, with no group repeated. For example, [1, 0, -1, 0, -2, 2] with target 0 gives [-2, -1, 1, 2], [-2, 0, 0, 2] and [-1, 0, 0, 1]. Values can be as large as 10⁹ in size.

The function name fourSum matches LeetCode. Use the link above for the exact statement. This guide lists each group in increasing order and the groups in sorted order.

Think first

  • How did 3Sum reduce to a pair problem? What does one more value add?
  • Four values of 10⁹ add up to 4 × 10⁹. Does that fit in a 32-bit int?
  • At which levels can repeated values cause repeated answers?

Hints

    Brute force, and why it fails

    Four nested loops: O(n⁴), which is 1.6 × 10¹³ for n = 200. Two loops plus a hash map of pair sums can be faster on average but makes removing repeated groups harder.

    The key insight

    k-Sum peels one value per loop until a pair is left, and the pair is solved with two pointers. 4Sum is two loops plus the pair search: O(n³).

    Dry run

    -20a
    -11b
    02left
    03 
    14 
    25right
    need3

    nums = [1, 0, -1, 0, -2, 2] and target = 0, sorted to [-2, -1, 0, 0, 1, 2]. Fix a = -2 and b = -1, so the last two must sum to 3.

    Step 1 of 5

    The plan

    sort nums
    for a from 0 to n - 4:
        if a > 0 and nums[a] == nums[a - 1]: continue
        for b from a + 1 to n - 3:
            if b > a + 1 and nums[b] == nums[b - 1]: continue
            left = b + 1, right = n - 1
            while left < right:
                sum = nums[a] + nums[b] + nums[left] + nums[right]     # 64-bit
                if sum < target: left = left + 1
                else if sum > target: right = right - 1
                else:
                    record the four values
                    left = left + 1; right = right - 1
                    skip left past repeats
    

    Complexity

    Time
    O(n³)
    Space
    O(1)

    n² choices of the first two values, each followed by an O(n) pair search. Only a few indexes are used besides the output.

    Edge cases

    • Fewer than four values: an empty list.
    • [2, 2, 2, 2, 2] with target 8: [[2, 2, 2, 2]] once.
    • Four values of 10⁹: their sum needs 64 bits.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<>();
            int n = nums.length;
            for (int a = 0; a < n - 3; a++) {
                if (a > 0 && nums[a] == nums[a - 1]) {
                    continue;
                }
                for (int b = a + 1; b < n - 2; b++) {
                    if (b > a + 1 && nums[b] == nums[b - 1]) {
                        continue;
                    }
                    int left = b + 1;
                    int right = n - 1;
                    while (left < right) {
                        long sum = (long) nums[a] + nums[b] + nums[left] + nums[right];   // can pass 32 bits
                        if (sum < target) {
                            left++;
                        } else if (sum > target) {
                            right--;
                        } else {
                            result.add(Arrays.asList(nums[a], nums[b], nums[left], nums[right]));
                            left++;
                            right--;
                            while (left < right && nums[left] == nums[left - 1]) {
                                left++;
                            }
                        }
                    }
                }
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            vector<vector<int>> result;
            int n = static_cast<int>(nums.size());
            for (int a = 0; a < n - 3; a++) {
                if (a > 0 && nums[a] == nums[a - 1]) {
                    continue;
                }
                for (int b = a + 1; b < n - 2; b++) {
                    if (b > a + 1 && nums[b] == nums[b - 1]) {
                        continue;
                    }
                    int left = b + 1;
                    int right = n - 1;
                    while (left < right) {
                        long long sum = static_cast<long long>(nums[a]) + nums[b] + nums[left] + nums[right];   // can pass 32 bits
                        if (sum < target) {
                            left++;
                        } else if (sum > target) {
                            right--;
                        } else {
                            result.push_back({nums[a], nums[b], nums[left], nums[right]});
                            left++;
                            right--;
                            while (left < right && nums[left] == nums[left - 1]) {
                                left++;
                            }
                        }
                    }
                }
            }
            return result;
        }
    };

    Python

    class Solution:
        def fourSum(self, nums: list[int], target: int) -> list[list[int]]:
            nums.sort()
            result = []
            n = len(nums)
            for a in range(n - 3):
                if a > 0 and nums[a] == nums[a - 1]:
                    continue
                for b in range(a + 1, n - 2):
                    if b > a + 1 and nums[b] == nums[b - 1]:
                        continue
                    left, right = b + 1, n - 1
                    while left < right:
                        total = nums[a] + nums[b] + nums[left] + nums[right]
                        if total < target:
                            left += 1
                        elif total > target:
                            right -= 1
                        else:
                            result.append([nums[a], nums[b], nums[left], nums[right]])
                            left += 1
                            right -= 1
                            while left < right and nums[left] == nums[left - 1]:
                                left += 1
            return result

    Common mistakes

    • Adding the four values in 32 bits, which overflows and finds wrong matches.
    • Skipping the second value with b > 0 instead of b > a + 1, which skips valid first choices of b.
    • Forgetting to skip repeats at one of the levels.

    Similar problems