Statement▼
Given an integer array, nums, find and return all unique triplets [nums[i], nums[j], nums[k]], such that i j, i k, and j k and nums[i] + nums[j] + nums[k]
Note: The order of the triplets in the output does not matter.
Constraints:
3≤ nums.length≤500 −103≤ nums[i]≤103
Solution
The essence of the solution lies in first sorting the array, which makes it easier to find positive numbers that balance out negative ones to sum to zero, and also helps in skipping duplicates. Then, for each number in the array, we search for two other numbers to the right that, together with it, sum to zero. This is done using two pointers—low and high—starting just after the fixed number and at the end of the array, respectively. We calculate the sum of each triplet as nums[i] + nums[low] + nums[high]. If the total is less than zero, we move the low pointer forward to increase the sum; if it’s greater than zero, we move the high pointer backward to decrease the sum. When the sum is exactly zero, we add the triplet to the result and move both pointers inward, skipping duplicates to ensure all triplets are unique.
Using the intuition above, we implement the algorithm as follows:
Sort the input array
numsin ascending order to make it easier to find triplets and skip duplicates.Create an empty array,
result, to store the unique triplets.Store the length of
numsin a variablen.Iterate over the array from index
i = 0ton - 2(as we are looking for triplets).Break the loop if the current number
nums[i]is greater than0. As the array is sorted, all remaining numbers will be positive, and any triplet includingnums[i]will have a sum greater than zero.If
i == 0ornums[i]is not equal tonums[i - 1], this ensures that the current number is either the first element or not a duplicate of the previous element.Initialize two pointers:
low = i + 1andhigh = n - 1.Run a loop as long as
lowis less thanhigh.Calculate the sum:
nums[i] + nums[low] + nums[high].If the sum is less than
0, move thelowpointer forward to increase the sum.If the sum is greater than
0, move thehighpointer backward to decrease the sum.Otherwise, add
[nums[i], nums[low], nums[high]]to theresult, as this triplet sums to0.Move
lowandhighto the next distinct values to avoid duplicate triplets. This is done by incrementinglowwhilenums[low] == nums[low - 1], and decrementinghighwhilenums[high] == nums[high + 1].
After iterating through the whole array, return the
resultthat contains all unique triplets that sum to zero.
Let’s look at the following illustration to get a better understanding of the solution: