Approach 1: Two-Pointer

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = set()
        nums.sort()
 
        for i, num1 in enumerate(nums):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            
            l, r = i + 1, len(nums) - 1
            while l < r:
                total = num1 + nums[l] + nums[r]
 
                if total > 0:
                    r -= 1
                elif total < 0:
                    l += 1
                else:
                    res.add((num1, nums[l], nums[r]))
                    l += 1
            
        return list(map(lambda x: list(x), res))

Complexity

Time:
Space:

Notes

This problem is similar to LC1. Two Sum on a sorted list. We need to fix the first number and run two-sum approach on the remaining elements in the air. It’s simpler to just use a set of tuples in Python’s case to avoid additional duplicate skipping logic in the loops and keep things somewhat clean.

Other Languages