Medium
Two Pointers
3Sum
Fix one number, then two-pointer the rest for its negation.
Approach
Sort the array. For each index i, use two pointers on the subarray to its right to find pairs summing to −nums[i]. Skip duplicate values for both the fixed element and the pointers to avoid repeated triples. Sorting makes both the search and dedupe straightforward.
Time complexity
O(n²)
Space complexity
O(1) or O(n) for the sort
Common mistake
Producing duplicate triples — you must skip equal adjacent values at every level, not just the outer loop.
See it run, step by step
Generate an interactive lesson for 3Sum — trace every variable and watch the algorithm execute until it clicks.
Start a lesson on 3Sum