3Sum

Find all unique triplets that sum to zero.

Pattern

Sort + Two Pointers

This problem follows the Sort + Two Pointers pattern, commonly found in the Two Pointers category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Sort array. Fix one element, use two pointers for the remaining pair. Skip duplicates.

Key Insight

Sorting first lets you use two pointers for the inner loop AND skip duplicates easily — without sorting you'd need a set of tuples.

Step-by-step

  1. 1Sort the array in ascending order
  2. 2Iterate i from 0 to n-2 (the fixed element)
  3. 3Skip duplicate values of nums[i] to avoid duplicate triplets
  4. 4Set left = i+1, right = n-1 and run two-pointer search
  5. 5If sum < 0, move left right; if sum > 0, move right left
  6. 6On match, add triplet and skip duplicates on both pointers

Pseudocode

sort(nums)
for i = 0 to n - 2:
    if i > 0 and nums[i] == nums[i-1]: continue
    left = i + 1, right = n - 1
    while left < right:
        sum = nums[i] + nums[left] + nums[right]
        if sum < 0: left++
        else if sum > 0: right--
        else:
            result.add([nums[i], nums[left], nums[right]])
            while left < right and nums[left] == nums[left+1]: left++
            while left < right and nums[right] == nums[right-1]: right--
            left++; right--
Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(1)
More Two Pointers Problems

Master this pattern with YeetCode

Practice 3Sum and similar Two Pointers problems with flashcards. Build pattern recognition through active recall.

Practice this problem