Problem Statement

3Sum

You get a list of whole numbers called nums. Your job is to find every group of three numbers in the list that add up to exactly zero. Each group of three is called a triplet. The three numbers must come from three different spots in the list (you cannot reuse the same spot twice). And you must not report the same triplet twice, even if it can be built from different spots. Return all the triplets you find.

mediumArrayTwo PointersSortingTwo PointersTime: O(n^2) · Space: O(1)

Signals to notice

find all triplets summing to zerosorted arrayavoid duplicates

Brute force first

Three nested loops checking every triplet. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Sort, fix one element, two-pointer scan for the other two. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on nums=[-1,0,1,2,-1,-4]

sort -> [-4,-1,-1,0,1,2]; result=[]
i=0(-4): L,R scan, totals -3..-1 all <0, L advances to meet R -> no triplet
i=1(-1): L=2(-1) R=5(2) total=0 -> push [-1,-1,2]; no dups; L=3 R=4
i=1 cont: L=3(0) R=4(1) total=0 -> push [-1,0,1]; L=4 R=3 -> stop
i=2(-1): nums[2]==nums[1] -> skip duplicate pivot
i=3(0): L=4(1) R=5(2) total=3>0 -> R-- to 4; L==R -> stop, no triplet
return [[-1,-1,2],[-1,0,1]]

What must stay true

Sort first, then for each element, use two pointers on the remaining array to find pairs summing to its negative. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

sort(nums)
for i in 0..n-3:
    if i>0 and nums[i]==nums[i-1]: continue   # skip dup pivot
    left, right = i+1, n-1
    while left < right:
        s = nums[i]+nums[left]+nums[right]
        if s<0: left++   elif s>0: right--
        else: record triplet; skip dups; left++; right--

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Duplicate triplets — skip elements equal to the previous one at each level. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Two Pointers Pattern