← DSA
MEDIUM

3Sum

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] (distinct indices) whose values sum to zero. The result must not contain duplicate triplets.

Example

Input nums = [-1,0,1,2,-1,-4]
Output [[-1,-1,2],[-1,0,1]]

Key Pointers

Step-by-Step Analysis

  1. Sort nums.
  2. For each index i: skip it if nums[i] == nums[i-1] (duplicate fixed value); stop entirely if nums[i] > 0, since a sorted positive start can't sum to zero.
  3. Set left = i + 1, right = len(nums) - 1, and run the two-pointer sweep from Two Sum II on the subarray.
  4. On a zero sum, record the triplet and advance both pointers past any duplicate values; on a negative sum move left forward, on a positive sum move right backward.

Complexity

Time: O(n²) — Space: O(1) extra, not counting the sort or the output

Code

def threeSum(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
        if nums[i] > 0:
            break

        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                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

    return result

Code Explanation

How the solution above works, piece by piece.

  1. nums.sort(): sorting puts equal values next to each other (easy duplicate skipping) and lets two pointers decide which way to move. The example becomes [-4, -1, -1, 0, 1, 2].
  2. for i in range(len(nums)): fix one number, nums[i]. Now we only need two more numbers that add up to -nums[i].
  3. if i > 0 and nums[i] == nums[i - 1]: continue: the same fixed value would find the same triplets again, so skip it.
  4. if nums[i] > 0: break: everything to the right is at least as big, so three positives can never sum to 0. Stop early.
  5. left, right = i + 1, len(nums) - 1: search the part after i from both ends.
  6. Compute total. If it is too small, left += 1 makes it bigger; if too big, right -= 1 makes it smaller. The array is sorted, so each move is the only one that can help.
  7. total == 0: record the triplet, move both pointers inward, then skip any repeated values on each side so the same triplet isn't added twice.
  8. Each i does one O(n) sweep, so O(n²) overall, and no extra set is needed for de-duplication.

Visual Walkthrough

Running the solution on nums = [-1, 0, 1, 2, -1, -4]:

3Sum trace on the sorted example-40-11-12031425sorted-4-1-1012i=0−3 < 0 → left++-4-1-1012i=0−3 < 0 → left++-4-1-1012i=0−2 < 0 → left++-4-1-1012i=0−1 < 0 → left++, pointers meet-4-1-1012i=10 → found [−1, −1, 2]-4-1-1012i=10 → found [−1, 0, 1]-4-1-1012i=2−1 same as previous → skip-4-1-1012i=33 > 0 → right--, pointers meet-4-1-1012i=41 > 0 → stop the whole loop
Each row is one check. Amber = the fixed number nums[i]; blue = left and right. The sum decides which pointer moves: too small → move left right, too big → move right left. Two triplets are found, both while i = 1.
fixed nums[i]left / rightskipped / stop

Video Explanation

NeetCode — 3Sum, LeetCode 15