LeetCode 15: 3Sum Explained

LeetCode 15: 3Sum Explained

LeetCode 15: 3Sum Explained

The "3Sum" problem is a classic LeetCode challenge that asks you to find all unique triplets in an array that add up to zero. In this post, I'll provide a detailed explanation and Python solution.

Problem Overview

Given an array `nums` of *n* integers, find all unique triplets (a, b, c) in `nums` such that a + b + c = 0.

Notice that the solution set must not contain duplicate triplets.

Solution

Here's an efficient Python function to solve the 3Sum problem:

def three_sum(nums):
    result = []
    nums.sort()  # Important: Sort the array

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:  # Skip duplicate elements
            continue

        left = i + 1
        right = len(nums) - 1

        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]

            if current_sum == 0:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1

                while left < right and nums[left] == nums[left - 1]:  # Skip duplicates
                    left += 1
                while left < right and nums[right] == nums[right + 1]:  # Skip duplicates
                    right -= 1
            elif current_sum < 0:
                left += 1
            else:
                right -= 1
    return result

This solution first sorts the input array, which is crucial for efficiency and for handling duplicates. It then iterates through the array, using each element `nums[i]` as a potential first element of a triplet. Two pointers, `left` and `right`, are used to find the other two elements that sum to `-nums[i]`. The code also includes logic to skip duplicate elements, ensuring that only unique triplets are included in the result.

Test Cases

>>> three_sum([-1, 0, 1, 2, -1, -4])
[[-1, -1, 2], [-1, 0, 1]]
>>> three_sum([])
[]
>>> three_sum([0, 0, 0])
[[0, 0, 0]]
>>> three_sum([-2,0,0,2,2])
[[-2, 0, 2]]

Conclusion

This post provides a clear explanation and an efficient Python solution for the LeetCode 3Sum problem. The use of sorting and two pointers makes this a relatively optimized approach. Handling duplicates is key to getting the correct result. I hope you found this helpful. Please leave any questions or comments below.

Comments

Popular posts from this blog

LeetCode Problem #10: Regular Expression Matching - Explanation and Solutions in Python and JavaScript

LeetCode Problem #1: Two Sum - Explanation and Solutions in Python and JavaScript

LeetCode Problem #2: Add Two Numbers - Explanation and Solutions in Python and JavaScript