3Sum in Python: Sorting and Two Pointers Explained

Sorted array with fixed -1, left -1 and right 2 forming zero; move pointers according to the sum.

Given an integer array, return every unique triplet of values whose sum is zero. Each triplet must use three distinct indices; the order of results does not matter. This medium-level interview problem combines sorting, two pointers and duplicate elimination. Unlike Two Sum, returning only the first match is not enough.

Example

[-1,0,1,2,-1,-4] gives [-1,-1,2] and [-1,0,1].

Pattern recognition and hints

Hint 1: Start by enumerating every combination of three indices.

Hint 2: Sort the array so increasing the left pointer increases or preserves the sum.

Hint 3: Fix one value and solve a two-pointer search on its suffix. Skip repeated anchors and repeated pointer values after a match.

Brute force

from itertools import combinations
def brute(nums):
    return sorted({tuple(sorted(t)) for t in combinations(nums,3)
                   if sum(t)==0})

The brute-force version checks every combination of three distinct indices. Sorting each matching triple makes it canonical; a set removes duplicates. It returns tuples, while the optimized implementation returns lists. Normalize the output when comparing them.

Optimized or iterative approach

Sort first, fix one element, and search the remaining suffix with two pointers.

def three_sum(nums):
    a = sorted(nums)
    out = []
    for i in range(len(a)-2):
        if i and a[i] == a[i-1]:
            continue
        if a[i] > 0:
            break
        l, r = i+1, len(a)-1
        while l < r:
            total = a[i]+a[l]+a[r]
            if total < 0:
                l += 1
            elif total > 0:
                r -= 1
            else:
                out.append([a[i],a[l],a[r]])
                l += 1
                r -= 1
                while l < r and a[l] == a[l-1]:
                    l += 1
                while l < r and a[r] == a[r+1]:
                    r -= 1
    return out

Pseudocode

SORT a copy of nums
FOR each anchor i through n-3:
  SKIP repeated anchors; STOP if anchor is positive
  SET left = i+1, right = n-1
  WHILE left < right:
    COMPUTE sum of anchor, left, right
    IF sum < 0: move left rightward
    ELSE IF sum > 0: move right leftward
    ELSE: record triplet, move both, skip duplicates
RETURN results

Step-by-step walkthrough

Sorted input: -4,-1,-1,0,1,2. Fix -1 at index 1; pointers find -1 and 2, then 0 and 1. Skip the next duplicate fixed value.

AnchorLeftRightSumAction
0 (-4)1 (-1)5 (2)-3Move left
0 (-4)2 (-1)5 (2)-3Move left
0 (-4)3 (0)5 (2)-2Move left
0 (-4)4 (1)5 (2)-1Move left; pointers meet
1 (-1)2 (-1)5 (2)0Record [-1,-1,2]; move both
1 (-1)3 (0)4 (1)0Record [-1,0,1]; move both
2 (-1)———Skip duplicate anchor
3 (0)4 (1)5 (2)3Move right; pointers meet

Correctness argument

In a sorted suffix, if the sum is too small, the current left value cannot work with any smaller right value. The symmetric argument applies to an excessive sum. Skipping equal values preserves distinct value triplets.

Every unique triplet has a smallest value that can serve as its anchor. Searching the sorted suffix covers all remaining candidates. After a match, repeating either matched value would only reproduce the same value triplet; moving both pointers and skipping equal values therefore loses no unique result.

Complexity analysis

Brute force enumerates O(n³) triples; set operations are expected constant time, and sorting k distinct results adds O(k log k) time. It stores O(k) results. The optimized algorithm sorts in O(n log n) time, then performs at most O(n) pointer movements for each of O(n) anchors: O(n²) total time. Python’s sorted copy and sorting workspace use O(n) auxiliary space, excluding the O(k) output.

Edge cases

Test [] and [1,2] → []; [0,0,0,0] → [[0,0,0]]; [1,2,3] → []; [-3,-2,-1] → []; [-2,0,0,2,2] → [[-2,0,2]]. Avoid using the same index twice or returning repeated triplets.

Interview follow-ups

Why skip duplicates after a match? They produce the same triplet. Why sort a copy? It preserves the caller’s input.

Can hashing solve 3Sum? Yes, a per-anchor hash set can find pairs in expected O(n²) time, but deduplication needs care.

Why stop at a positive anchor? All subsequent sorted values are positive, so their sum cannot be zero.

How would you generalize? For 4Sum, fix two values and use two pointers for the remaining pair; handle duplicates at each level.

Practice and revision

Original problem · DSA Roadmap

Scroll to Top