0% found this document useful (0 votes)
7 views

LeetCode Solution

Uploaded by

saxena.akarsh5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

LeetCode Solution

Uploaded by

saxena.akarsh5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Sure, I'd be delighted to walk you through solving this problem step-by-step in Python.

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.

Here's the detailed and commented solution:

```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

# Now use two pointers to find the other two elements


left = i + 1 # The pointer for the second element
right = n - 1 # The pointer for the third element

while left < right:


current_sum = nums[i] + nums[left] + nums[right]

if current_sum == 0:
# Found a triplet that sums to zero, add it to the result
result.append([nums[i], nums[left], nums[right]])

# Move the left pointer to the right, skip duplicates


while left < right and nums[left] == nums[left + 1]:
left += 1
# Move the right pointer to the left, skip duplicates
while left < right and nums[right] == nums[right - 1]:
right -= 1

# Move both pointers to continue searching for other pairs


left += 1
right -= 1

elif current_sum < 0:


# If current_sum is less than 0, we need a larger number
left += 1
else:
# If current_sum is more than 0, we need a smaller number
right -= 1

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!

You might also like