Given an integer array nums
, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = [0,1,1]
Output: []
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Constraints:
3 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5
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:
The problem asks us to find combinations of three numbers that add up to zero. The brute force method means we will check every single possible combination of three numbers from the given set. If a combination adds up to zero, we keep it; otherwise, we move on to the next combination.
Here's how the algorithm would work step-by-step:
def three_sum_brute_force(numbers):
result = []
numbers_length = len(numbers)
for first_index in range(numbers_length):
for second_index in range(first_index + 1, numbers_length):
for third_index in range(second_index + 1, numbers_length):
first_number = numbers[first_index]
second_number = numbers[second_index]
third_number = numbers[third_index]
sum_of_numbers = first_number + second_number + third_number
# Check if the current combination sums to zero.
if sum_of_numbers == 0:
current_combination = sorted([first_number, second_number, third_number])
# Avoid adding duplicate triplets to the result.
if current_combination not in result:
result.append(current_combination)
# Return the unique triplets that sum to zero.
return result
The key to efficiently finding sets of three numbers that sum to zero involves avoiding redundant calculations by strategically narrowing down possibilities. First we sort the numbers, then we use a two-pointer approach to quickly explore potential pairs that complement a fixed number.
Here's how the algorithm would work step-by-step:
def find_triplets_that_sum_to_zero(numbers):
numbers.sort()
triplets = []
numbers_length = len(numbers)
for i in range(numbers_length - 2):
# Avoid duplicates for the first number
if i > 0 and numbers[i] == numbers[i - 1]:
continue
left_pointer = i + 1
right_pointer = numbers_length - 1
while left_pointer < right_pointer:
current_sum = numbers[i] + numbers[left_pointer] + numbers[right_pointer]
if current_sum == 0:
triplets.append([numbers[i], numbers[left_pointer], numbers[right_pointer]])
# Avoid duplicates for the second number
while left_pointer < right_pointer and numbers[left_pointer] == numbers[left_pointer + 1]:
left_pointer += 1
# Avoid duplicates for the third number
while left_pointer < right_pointer and numbers[right_pointer] == numbers[right_pointer - 1]:
right_pointer -= 1
left_pointer += 1
right_pointer -= 1
elif current_sum < 0:
left_pointer += 1 # Need a larger sum
else:
right_pointer -= 1 # Need a smaller sum
return triplets
Case | How to Handle |
---|---|
Null or empty input array | Return an empty list immediately as no triplets can be formed. |
Array with less than 3 elements | Return an empty list since a triplet cannot be formed. |
Array with all identical numbers (e.g., all zeros) | The solution should handle duplicate values correctly, ensuring only unique triplets are added to the result, and avoiding issues like [0, 0, 0], [0, 0, 0], etc. |
Array with many duplicate numbers | The solution must avoid generating duplicate triplets by skipping over consecutive duplicate numbers after sorting the array. |
Array with large positive and negative numbers that could potentially lead to integer overflow during summation | Using a language with automatic overflow handling or employing appropriate checks within the summation can prevent potential overflow errors. |
Array contains a large number of zeros. | The solution should handle the case where multiple zeros are present in the array, ensuring that triplets containing zeros are identified and duplicates are avoided. |
No triplets sum to zero. | The solution should return an empty list if no such triplets exist. |
Input array is very large (potential performance bottleneck) | Sorting the array first (O(n log n)) and then using two pointers to find triplets (O(n^2)) ensures an optimal solution with a time complexity of O(n^2). |