3Sum

Problem Link

Approach

Sort the array first so duplicate triplets are easy to skip and two-pointer search is possible.

Fix the first index i and run two pointers on the remaining range:

  • If the sum of the three values is zero, record the triplet and advance both pointers while skipping duplicates.
  • If the sum is too small, move the left pointer right.
  • If the sum is too large, move the right pointer left.

Skip duplicate values for i as well so the same triplet is not added twice.

A triple nested loop takes O(n³) time. Sorting plus two pointers reduces the work to O(n²).

Time Complexity: O(n²)
Space Complexity: O(1) extra space excluding output and sort storage

Code

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        result = []

        for i in range(len(nums)):
            if i > 0 and nums[i] == nums[i - 1]:
                continue

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

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

                if total == 0:
                    result.append([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
                    while left < right and nums[right] == nums[right + 1]:
                        right -= 1
                elif total < 0:
                    left += 1
                else:
                    right -= 1

        return result