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
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:
We need to find four numbers from a given set that add up to a specific target value. The brute force method is like trying every possible combination of four numbers and checking if that combination hits the target.
Here's how the algorithm would work step-by-step:
def four_sum_brute_force(numbers, target):
list_of_valid_quadruplets = []
for first_index in range(len(numbers)):
for second_index in range(first_index + 1, len(numbers)):
for third_index in range(second_index + 1, len(numbers)):
for fourth_index in range(third_index + 1, len(numbers)):
# We have a combination; now check the sum
sum_of_quadruplet = numbers[first_index] + numbers[second_index] +\
numbers[third_index] + numbers[fourth_index]
if sum_of_quadruplet == target:
# We need to sort to easily identify duplicates
quadruplet = sorted([numbers[first_index], numbers[second_index],\
numbers[third_index], numbers[fourth_index]])
# Check if this sorted quadruplet is already in our results
if quadruplet not in list_of_valid_quadruplets:
# Avoid duplicates in our final answer
list_of_valid_quadruplets.append(quadruplet)
return list_of_valid_quadruplets
The most efficient way to solve this is to avoid checking every possible combination. Instead, we use a clever ordering and narrowing of our search to quickly find the groups of four numbers that add up to the target. This involves sorting the numbers and strategically moving through them.
Here's how the algorithm would work step-by-step:
def four_sum(numbers, target):
numbers.sort()
quadruplets = []
number_of_elements = len(numbers)
for first_number_index in range(number_of_elements - 3):
# Prevents duplicate quadruplets in result
if first_number_index > 0 and numbers[first_number_index] == numbers[first_number_index - 1]:
continue
for second_number_index in range(first_number_index + 1, number_of_elements - 2):
# Prevents duplicate quadruplets in result
if second_number_index > first_number_index + 1 and numbers[second_number_index] == numbers[second_number_index - 1]:
continue
left_number_index = second_number_index + 1
right_number_index = number_of_elements - 1
while left_number_index < right_number_index:
current_sum = numbers[first_number_index] + numbers[second_number_index] + numbers[left_number_index] + numbers[right_number_index]
if current_sum == target:
quadruplets.append([numbers[first_number_index], numbers[second_number_index], numbers[left_number_index], numbers[right_number_index]])
# Avoids duplicate triplets
while left_number_index < right_number_index and numbers[left_number_index] == numbers[left_number_index + 1]:
left_number_index += 1
# Avoids duplicate triplets
while left_number_index < right_number_index and numbers[right_number_index] == numbers[right_number_index - 1]:
right_number_index -= 1
left_number_index += 1
right_number_index -= 1
elif current_sum < target:
# Sum is too small, move left pointer to increase sum.
left_number_index += 1
else:
# Sum is too large, move right pointer to decrease sum.
right_number_index -= 1
return quadruplets
Case | How to Handle |
---|---|
Null input array | Throw an IllegalArgumentException or return an empty list to avoid NullPointerException. |
Array size less than 4 | Return an empty list since a 4-sum combination is impossible. |
Input array with all identical numbers. | Correctly handles duplicate numbers by skipping over same elements in inner loops after the first occurence for each distinct number. |
Large input array with numbers close to INT_MAX or INT_MIN. | Potential integer overflow during summation, consider using long data type for intermediate sums. |
Target value is extremely large or small. | The algorithm should still function correctly, assuming no integer overflow during sum calculation. |
No valid 4-sum combinations exist. | Return an empty list to indicate that no solution was found. |
Input array contains duplicate quadruplets that sum to the target. | Sort each quadruplet and add it to a set to avoid duplicate quadruplets in the result. |
Presence of zero in the input array. | Handle zero appropriately; including it may or may not lead to a valid quadruplet so ensure the counts of zero are correctly handled. |