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 < na, b, c, and d are distinct.nums[a] + nums[b] + nums[c] + nums[d] == targetYou 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 <= 109When 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:
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:
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]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:
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| Case | How to Handle |
|---|---|
| Array with fewer than four elements | Return an empty list immediately because a quadruplet requires at least four elements. |
| Integer overflow during addition of four numbers | Cast the array elements to 64-bit integers before summing to prevent arithmetic overflow. |
| Array containing many duplicate values | 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 | The duplication check ensures only one unique quadruplet is added to the final result set. |
| Negative numbers mixed with zeros and positive numbers | Sorting the array first allows the two-pointer approach to correctly navigate negative and positive ranges. |
| No valid quadruplets exist in the array | The algorithm will exhaustively check all combinations and correctly return an empty list. |
| Multiple valid quadruplets with overlapping elements | The two-pointer inner loops continue scanning and advancing past duplicates to find all distinct combinations. |
| Extremely large array size causing time limit exceeded | The O(n cubed) sorting and pointer approach efficiently scales without excessive memory overhead. |