Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] where i, j, and k are distinct indices, such that the three elements sum to zero.
The result must not contain any duplicate triplets. The order of the output and the order of elements within each triplet does not matter.
Note: The solution set must only include unique triplets. Two triplets are considered duplicates if they contain the same elements regardless of ordering.
Constraints:
nums.length
nums[i]
The key intuition behind this solution is to reduce the nums[i], we need to find two other elements in the remaining portion of the array that sum to -nums[i]. Since the array is sorted, we place a left pointer just after index i and a right pointer at the end of the array. If the current sum of the three elements is too small, we move left rightward to increase the sum; if too large, we move right leftward to decrease it. When we find a valid triplet, we record it and skip any duplicate values for both pointers to ensure uniqueness in the result.
Now, let’s look at the solution steps below:
Sort the input array nums in ascending order. This enables the two pointer approach and makes it straightforward to skip duplicate elements.
Initialize an empty list result to store all unique triplets.
Iterate through the array with index i from
Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] where i, j, and k are distinct indices, such that the three elements sum to zero.
The result must not contain any duplicate triplets. The order of the output and the order of elements within each triplet does not matter.
Note: The solution set must only include unique triplets. Two triplets are considered duplicates if they contain the same elements regardless of ordering.
Constraints:
nums.length
nums[i]
The key intuition behind this solution is to reduce the nums[i], we need to find two other elements in the remaining portion of the array that sum to -nums[i]. Since the array is sorted, we place a left pointer just after index i and a right pointer at the end of the array. If the current sum of the three elements is too small, we move left rightward to increase the sum; if too large, we move right leftward to decrease it. When we find a valid triplet, we record it and skip any duplicate values for both pointers to ensure uniqueness in the result.
Now, let’s look at the solution steps below:
Sort the input array nums in ascending order. This enables the two pointer approach and makes it straightforward to skip duplicate elements.
Initialize an empty list result to store all unique triplets.
Iterate through the array with index i from