Taro Logo

4Sum

#81 Most AskedMedium
Topics:
ArraysTwo Pointers

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

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

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in the nums array, and can the sum of four numbers exceed the standard 32-bit integer limits requiring 64-bit integers?
  2. Should the quadruplets themselves and the overall list of quadruplets be returned in any specific sorted order?
  3. What should be returned if fewer than 4 elements are provided in the input array or if no valid quadruplets are found?
  4. Can the same element index be used multiple times within a single quadruplet, or must all four elements come from distinct indices?
  5. Are there any specific time or space complexity constraints I should aim for beyond the optimal $O(n^3)$ approach?

Brute Force Solution

Approach

Imagine you are given a massive collection of items, and you need to find every unique combination of four distinct items that together add up to a specific target value. The brute force approach relies on checking every conceivable group of four items to see if their combined total matches the goal.

Here's how the algorithm would work step-by-step:

  1. Begin by picking the very first item from your collection.
  2. Pair it with a second item, then a third item, and finally a fourth item to form a unique group of four.
  3. Calculate the total combined value of this specific group of four items.
  4. Check if this total matches the exact target value you are trying to reach.
  5. If the total matches your target, write down this group of four items as a successful find, making sure you have not recorded the exact same group previously.
  6. Shift your selections to try the next possible combination of four items, moving systematically through every single grouping option available in the collection.
  7. Repeat this checking process for every single unique group of four until you have exhausted all possible combinations.

Code Implementation

class Solution:
    def fourSum(self, numbers: list[int], target_value: int) -> list[list[int]]:
        found_combinations_set = set()
        collection_length = len(numbers)
        
        # Exhaustively check every possible quadruplet to ensure we do not miss any valid combinations
        for first_index in range(collection_length):
            for second_index in range(first_index + 1, collection_length):
                for third_index in range(second_index + 1, collection_length):
                    for fourth_index in range(third_index + 1, collection_length):
                        
                        current_first = numbers[first_index]
                        current_second = numbers[second_index]
                        current_third = numbers[third_index]
                        current_fourth = numbers[fourth_index]
                        
                        combined_total = current_first + current_second + current_third + current_fourth
                        
                        # Validate if the calculated sum matches our target value before recording the group
                        if combined_total == target_value:
                            sorted_quadruplet = tuple(sorted([current_first, current_second, current_third, current_fourth]))
                            found_combinations_set.add(sorted_quadruplet)
                            
        # Convert our set of unique tuples back into a list of lists to satisfy the expected return format
        return [list(quadruplet) for quadruplet in found_combinations_set]

Big(O) Analysis

Time Complexity
O(n⁴) – The brute force approach uses four nested loops, where each loop iterates through the collection of n items to select one of the four distinct elements for a combination. For the first item we iterate through n options, for the second we iterate through n minus one options, and this multiplicative nesting continues for all four positions. This results in approximately n times n minus one times n minus two times n minus three divided by twenty-four operations. Simplifying this polynomial yields a Big O time complexity of O(n⁴).
Space Complexity
O(N^3) – The primary driver of auxiliary space is the storage required for unique quadruplets that match the target value. In the worst-case scenario, the number of valid quadruplets scales cubically with the input size N. Additionally, the algorithm maintains pointers and temporary variables whose memory footprint is negligible compared to the result set. Consequently, the total extra memory needed to record all successful finds grows asymptotically as the cube of the input size N.

Optimal Solution

Approach

Instead of blindly testing every possible combination of four numbers, the optimal approach first sorts all the numbers to bring order to the chaos. This organization allows us to systematically pair up numbers and efficiently hunt for the remaining two values using clever boundary adjustments.

Here's how the algorithm would work step-by-step:

  1. Sort all the available numbers from smallest to largest so that you can easily navigate them and avoid repeating identical groups.
  2. Pick a starting number as your first anchor, making sure to skip over duplicate values so you do not repeat the same work.
  3. Pick a second number just after the first anchor, again skipping any duplicates to keep your choices unique.
  4. With your first two numbers locked in, set up two boundary markers for the remaining portion: one starting immediately after your second number and the other sitting at the very end of all the numbers.
  5. Calculate the sum of your four chosen numbers and compare it against the target goal you want to reach.
  6. If the total sum is too small, move your lower boundary marker up to increase the total.
  7. If the total sum is too large, move your upper boundary marker down to decrease the total.
  8. If the total sum matches your target goal, save this successful group of four numbers, and then adjust both boundary markers inward while skipping duplicates to find other possible matches.
  9. Continue this process by shifting your second number and eventually your first anchor until every possibility has been smartly explored.

Code Implementation

class Solution:
    def fourSum(self, numbers_list: list[int], target_goal: int) -> list[list[int]]:
        sorted_numbers = sorted(numbers_list)
        total_count = len(sorted_numbers)
        quadruplets_result = []

        # Sorting brings order and enables skipping duplicates to avoid redundant work.
        for first_index in range(total_count - 3):
            if first_index > 0 and sorted_numbers[first_index] == sorted_numbers[first_index - 1]:
                continue

            for second_index in range(first_index + 1, total_count - 2):
                if second_index > first_index + 1 and sorted_numbers[second_index] == sorted_numbers[second_index - 1]:
                    continue

                lower_boundary = second_index + 1
                upper_boundary = total_count - 1

                while lower_boundary < upper_boundary:
                    current_sum = (
                        sorted_numbers[first_index]
                        + sorted_numbers[second_index]
                        + sorted_numbers[lower_boundary]
                        + sorted_numbers[upper_boundary]
                    )

                    # Boundary markers adjust inward to systematically search for the target sum.
                    if current_sum < target_goal:
                        lower_boundary += 1
                    elif current_sum > target_goal:
                        upper_boundary -= 1
                    else:
                        quadruplets_result.append([
                            sorted_numbers[first_index],
                            sorted_numbers[second_index],
                            sorted_numbers[lower_boundary],
                            sorted_numbers[upper_boundary]
                        ])

                        lower_boundary += 1
                        upper_boundary -= 1

                        # Skip duplicates on boundaries to find unique subsequent combinations.
                        while lower_boundary < upper_boundary and sorted_numbers[lower_boundary] == sorted_numbers[lower_boundary - 1]:
                            lower_boundary += 1

                        while lower_boundary < upper_boundary and sorted_numbers[upper_boundary] == sorted_numbers[upper_boundary + 1]:
                            upper_boundary -= 1

        return quadruplets_result

Big(O) Analysis

Time Complexity
O(n³) – The initial sorting step takes O(n log n) time, which is quickly dominated by the subsequent nested traversal. We use a first loop to pick the anchor element and a second inner loop to pick the second number across the n elements. For every unique pair of these first two numbers, the two boundary markers scan the remaining elements in linear time. This combination yields approximately n * n * n operations, which simplifies to the final cubic time complexity of O(n³).
Space Complexity
O(1) – Beyond the space needed to store the output results, the auxiliary memory consists entirely of a few primitive pointer variables used for the anchors and boundary markers. Since the sorting operation is performed in place on the input array, no additional data structures scale with the input size N. Therefore, the extra memory used by the algorithm remains constant regardless of how many elements are in the input.

Edge Cases

Array with fewer than four elements
How to Handle:
Return an empty list immediately because a quadruplet requires at least four elements.
Integer overflow during addition of four numbers
How to Handle:
Cast the array elements to 64-bit integers before summing to prevent arithmetic overflow.
Array containing many duplicate values
How to Handle:
Skip identical adjacent elements during the outer loops and after finding a match to avoid duplicate quadruplets.
All elements are identical and match the target requirement
How to Handle:
The duplication check ensures only one unique quadruplet is added to the final result set.
Negative numbers mixed with zeros and positive numbers
How to Handle:
Sorting the array first allows the two-pointer approach to correctly navigate negative and positive ranges.
No valid quadruplets exist in the array
How to Handle:
The algorithm will exhaustively check all combinations and correctly return an empty list.
Multiple valid quadruplets with overlapping elements
How to Handle:
The two-pointer inner loops continue scanning and advancing past duplicates to find all distinct combinations.
Extremely large array size causing time limit exceeded
How to Handle:
The O(n cubed) sorting and pointer approach efficiently scales without excessive memory overhead.
0/245 completed