3Sum
Module 10 · Two Pointers
Problem
Given nums, return all unique triplets summing to zero. The answer
must contain no duplicate triplets (regardless of order).
Examples
Example 1
Input
nums = [-1,0,1,2,-1,-4]Output[[-1,-1,2], [-1,0,1]]Example 2
Input
nums = [0,1,1]Output[]Example 3
Input
nums = [0,0,0]Output[[0,0,0]]Constraints
3 ≤ n ≤ 3000 · values in ±10⁵.
Attempt it first
The classic composition problem: reduce 3Sum to n instances of a problem you've already solved. Two designs compete (hash-based and sort-based); the sort-based one wins here for a reason worth discovering — the duplicate handling, which is 3Sum's real difficulty and the reason interviewers love it.