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]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.
Constraints:
3 <= nums.length <= 3000-105 <= nums[i] <= 105When 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 collection of numbers and need to find every unique group of three numbers that add up to zero. The brute force approach is the most straightforward way to solve this by testing every single possible combination of three numbers to see which ones work.
Here's how the algorithm would work step-by-step:
def three_sum(number_collection):
successful_trios = set()
# We test every possible combination of three numbers by iterating through all index triplets
for first_index in range(len(number_collection)):
for second_index in range(first_index + 1, len(number_collection)):
for third_index in range(second_index + 1, len(number_collection)):
current_sum = number_collection[first_index] + number_collection[second_index] + number_collection[third_index]
# We check if the sum equals zero to satisfy the core requirement of the problem
if current_sum == 0:
current_trio = tuple(sorted([number_collection[first_index], number_collection[second_index], number_collection[third_index]]))
successful_trios.add(current_trio)
# Converting the set of tuples back into a list of lists ensures the expected output format
return [list(trio) for trio in successful_trios]Instead of testing every possible combination of three items, the optimal approach organizes everything in order first. This clever arrangement allows us to sweep through systematically and find matching groups with much less effort.
Here's how the algorithm would work step-by-step:
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
collected_triplets = []
nums.sort()
# Sorting allows us to use two pointers and efficiently skip duplicate values.
for index in range(len(nums)):
if index > 0 and nums[index] == nums[index - 1]:
continue
left_seeker = index + 1
right_seeker = len(nums) - 1
while left_seeker < right_seeker:
current_sum = nums[index] + nums[left_seeker] + nums[right_seeker]
if current_sum == 0:
collected_triplets.append([nums[index], nums[left_seeker], nums[right_seeker]])
left_seeker += 1
right_seeker -= 1
# Skipping duplicates here prevents adding identical triplets to our result.
while left_seeker < right_seeker and nums[left_seeker] == nums[left_seeker - 1]:
left_seeker += 1
while left_seeker < right_seeker and nums[right_seeker] == nums[right_seeker + 1]:
right_seeker -= 1
elif current_sum < 0:
left_seeker += 1
else:
right_seeker -= 1
# Returning all unique triplets found that sum up to zero.
return collected_triplets| Case | How to Handle |
|---|---|
| Array with fewer than three elements | Return an empty list immediately since it is impossible to form a triplet. |
| Array containing all zeros | The sorting and two-pointer approach correctly finds the single unique triplet [0, 0, 0] and skips subsequent duplicates. |
| All negative or all positive numbers | The pointer logic will naturally fail to find any sums equal to zero and return an empty list. |
| Input with many duplicate values | Skipping adjacent duplicate elements after processing prevents the generation of duplicate triplets in the result set. |
| No valid triplets exist that sum to zero | The algorithm safely completes execution and returns an empty list. |
| Multiple overlapping valid triplets | Moving both left and right pointers inward while skipping duplicates ensures all unique combinations are captured. |
| Maximum sized inputs up to thousands of elements | Sorting the array first allows an O(N^2) two-pointer scan which easily scales within time limits compared to an O(N^3) brute force. |
| Extreme boundary values near integer limits | Standard integer addition is safe here because typical array constraints prevent overflow during the summation of three standard integers. |