SDE & MLE Prep

15. 3Sum

Problem

Return every distinct triplet [a, b, c] of values from nums, taken from three different positions, with a + b + c = 0. The answer must not contain duplicate triplets; order doesn't matter.

Example: [-1,0,1,2,-1,-4] → [[-1,-1,2],[-1,0,1]]

Constraints: 3 ≤ n ≤ 3000.

Sort. Fix nums[i], then run Two Sum II on the suffix for -nums[i]. Skip equal neighbours (for i and after a hit) to avoid duplicate triplets. Stop early when nums[i] > 0.

sorted: [-4, -1, -1, 0, 1, 2]
i=-1:    l=-1 ............ r=2   -1+(-1)+2 = 0  ✓ -> [-1,-1,2]
         l=0 ......r=1           -1+0+1   = 0  ✓ -> [-1,0,1]
i=-1 (dup) skip

Complexity: O(n²) time, O(1) extra (besides sort).

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        for i in range(len(nums) - 2):
            if nums[i] > 0:
                break
            if i and nums[i] == nums[i - 1]:
                continue
            l, r = i + 1, len(nums) - 1
            while l < r:
                s = nums[i] + nums[l] + nums[r]
                if s < 0:
                    l += 1
                elif s > 0:
                    r -= 1
                else:
                    res.append([nums[i], nums[l], nums[r]])
                    l += 1
                    while l < r and nums[l] == nums[l - 1]:
                        l += 1
                    r -= 1
        return res