LeetCode Solution
LeetCode Solution
The
problem is to find all unique triplets in an array of integers that sum up to zero. Here's how
you can approach it:
1. **Sort the Array**: Sorting helps in efficiently finding triplets using a two-pointer
technique.
2. **Iterate with a Loop**: Use a loop to fix the first element of the triplet.
3. **Two-Pointer Technique**: For the remaining two elements, use two pointers to find pairs
that sum up to the negative value of the fixed element.
4. **Skip Duplicates**: Ensure that you don't include duplicate triplets in the output.
```python
def threeSum(nums):
# Step 1: Sort the array to simplify finding triplets and handling duplicates
nums.sort()
result = [] # This will store the list of triplets
n = len(nums)
# Step 2: Loop through each number considering it as the first element of the triplet
for i in range(n):
# Skip the same element to avoid duplicate triplets in the result
if i > 0 and nums[i] == nums[i - 1]:
continue
if current_sum == 0:
# Found a triplet that sums to zero, add it to the result
result.append([nums[i], nums[left], nums[right]])
return result
# Example usage:
nums = [-1, 0, 1, 2, -1, -4]
print(threeSum(nums)) # Output: [[-1, -1, 2], [-1, 0, 1]]
```
### Explanation:
1. **Sorting**: The array is sorted to facilitate the two-pointer technique and handle
duplicates easily.
2. **Main Loop**: We iterate through the array, treating each element as the first item of the
triplet. The index `i` represents the current element.
3. **Two Pointers**: The `left` pointer starts just after `i` and the `right` pointer starts at
the end of the array.
4. **Sum Check**:
- If the sum of array elements at indices `i`, `left`, and `right` equals zero, a valid triplet
is found. Then, duplicates are skipped by moving the left and right pointers.
- If the sum is less than zero, we need a larger value, so `left` is incremented.
- If the sum is more than zero, we need a smaller value, so `right` is decremented.
By following these steps, our approach efficiently finds all unique triplets summing to zero in
the given array. I hope this detailed solution and explanation help you understand how to solve
the problem!