KatInterview

18. 4Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all unique quadruplets in an array nums that sum up to a given target. The main challenges are:

Solution

4Sum in Python

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        if n < 4:
            return []

        # Sort the array to use the two-pointer technique and handle duplicates easily.
        nums.sort()
        result = []

        # Outer loop for the first number of the quadruplet.
        for i in range(n - 3):
            # Skip duplicate values for the first number.
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            # Pruning: if the smallest possible sum from this point is greater than target, break.
            # Python's integers have arbitrary precision, so overflow is not an issue.
            if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
                break
            
            # Pruning: if the largest possible sum with nums[i] is smaller than target, continue.
            if nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target:
                continue

            # Second loop for the second number.
            for j in range(i + 1, n - 2):
                # Skip duplicate values for the second number.
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue

                # Pruning for the second number.
                if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
                    break
                if nums[i] + nums[j] + nums[n - 2] + nums[n - 1] < target:
                    continue

                left, right = j + 1, n - 1

                # Two-pointer approach for the last two numbers.
                while left < right:
                    current_sum = nums[i] + nums[j] + nums[left] + nums[right]

                    if current_sum == target:
                        result.append([nums[i], nums[j], nums[left], nums[right]])

                        # Skip duplicates for the third number.
                        left += 1
                        while left < right and nums[left] == nums[left - 1]:
                            left += 1
                        
                        # Skip duplicates for the fourth number.
                        right -= 1
                        while left < right and nums[right] == nums[right + 1]:
                            right -= 1
                    elif current_sum < target:
                        left += 1
                    else:  # current_sum > target
                        right -= 1
        
        return result

4Sum in Java

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length < 4) {
            return result;
        }

        // Sort the array to use the two-pointer technique and handle duplicates easily.
        Arrays.sort(nums);
        int n = nums.length;

        // Outer loop for the first number of the quadruplet.
        for (int i = 0; i < n - 3; i++) {
            // Skip duplicate values for the first number.
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            // Pruning: if the smallest possible sum from this point is greater than target, break.
            if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }

            // Pruning: if the largest possible sum with nums[i] is smaller than target, continue.
            if ((long) nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) {
                continue;
            }

            // Second loop for the second number.
            for (int j = i + 1; j < n - 2; j++) {
                // Skip duplicate values for the second number.
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }

                // Pruning for the second number.
                if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if ((long) nums[i] + nums[j] + nums[n - 2] + nums[n - 1] < target) {
                    continue;
                }

                int left = j + 1;
                int right = n - 1;

                // Two-pointer approach for the last two numbers.
                while (left < right) {
                    long currentSum = (long) nums[i] + nums[j] + nums[left] + nums[right];

                    if (currentSum == target) {
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));

                        // Skip duplicates for the third number.
                        left++;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }

                        // Skip duplicates for the fourth number.
                        right--;
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    } else if (currentSum < target) {
                        left++;
                    } else { // currentSum > target
                        right--;
                    }
                }
            }
        }
        return result;
    }
}

4Sum in C++

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        int n = nums.size();
        if (n < 4) {
            return result;
        }

        // Sort the array to use the two-pointer technique and handle duplicates easily.
        sort(nums.begin(), nums.end());

        // Outer loop for the first number of the quadruplet.
        for (int i = 0; i < n - 3; ++i) {
            // Skip duplicate values for the first number.
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            // Pruning: if the smallest possible sum from this point is greater than target, break.
            if ((long long)nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }

            // Pruning: if the largest possible sum with nums[i] is smaller than target, continue.
            if ((long long)nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) {
                continue;
            }

            // Second loop for the second number.
            for (int j = i + 1; j < n - 2; ++j) {
                // Skip duplicate values for the second number.
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }

                // Pruning for the second number.
                if ((long long)nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if ((long long)nums[i] + nums[j] + nums[n - 2] + nums[n - 1] < target) {
                    continue;
                }

                int left = j + 1;
                int right = n - 1;

                // Two-pointer approach for the last two numbers.
                while (left < right) {
                    long long currentSum = (long long)nums[i] + nums[j] + nums[left] + nums[right];

                    if (currentSum == target) {
                        result.push_back({nums[i], nums[j], nums[left], nums[right]});

                        // Skip duplicates for the third number.
                        left++;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }

                        // Skip duplicates for the fourth number.
                        right--;
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    } else if (currentSum < target) {
                        left++;
                    } else { // currentSum > target
                        right--;
                    }
                }
            }
        }
        return result;
    }
};

4Sum in TypeScript

function fourSum(nums: number[], target: number): number[][] {
    const result: number[][] = [];
    const n = nums.length;
    if (n < 4) {
        return result;
    }

    // Sort the array to use the two-pointer technique and handle duplicates easily.
    nums.sort((a, b) => a - b);

    // Outer loop for the first number of the quadruplet.
    for (let i = 0; i < n - 3; i++) {
        // Skip duplicate values for the first number.
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }

        // Pruning: if the smallest possible sum from this point is greater than target, break.
        // JavaScript's `number` type is 64-bit float, safe for these integer ranges.
        if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
            break;
        }

        // Pruning: if the largest possible sum with nums[i] is smaller than target, continue.
        if (nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) {
            continue;
        }

        // Second loop for the second number.
        for (let j = i + 1; j < n - 2; j++) {
            // Skip duplicate values for the second number.
            if (j > i + 1 && nums[j] === nums[j - 1]) {
                continue;
            }

            // Pruning for the second number.
            if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                break;
            }
            if (nums[i] + nums[j] + nums[n - 2] + nums[n - 1] < target) {
                continue;
            }

            let left = j + 1;
            let right = n - 1;

            // Two-pointer approach for the last two numbers.
            while (left < right) {
                const currentSum = nums[i] + nums[j] + nums[left] + nums[right];

                if (currentSum === target) {
                    result.push([nums[i], nums[j], nums[left], nums[right]]);

                    // Skip duplicates for the third number.
                    left++;
                    while (left < right && nums[left] === nums[left - 1]) {
                        left++;
                    }

                    // Skip duplicates for the fourth number.
                    right--;
                    while (left < right && nums[right] === nums[right + 1]) {
                        right--;
                    }
                } else if (currentSum < target) {
                    left++;
                } else { // currentSum > target
                    right--;
                }
            }
        }
    }
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.