3Sum
Sort, then fix one element and two-pointer the rest. That turns the third loop into a linear scan, so the whole thing is O(n²) rather than O(n³). Sorting also puts duplicates next to each other, which is what makes deduplication a cheap skip instead of a set of tuples.
Overview
Reducing the third loop
The brute force is three nested loops, O(n³). Fix the first element and the problem becomes "find two numbers summing to -values[i]" — which is Two Sum, and on sorted input Two Sum is two pointers in O(n).
n iterations of an O(n) inner scan is O(n²), and the sort is O(n log n) so it disappears into that. Using a hash map for the inner search is also O(n²), and then deduplication is much harder — which is the argument for sorting.
Step through it
What to watch
- One element is fixed; the other two converge.
- A repeated fixed value is skipped, or the same triple is reported twice.
- The pointers only ever move inwards — that is the linear inner scan.
Say this out loud
"Sort, then for each index run two pointers over the rest looking for the complement. O(n²) time, O(1) extra space. Sorting also means duplicates are adjacent, so I skip them rather than deduplicating at the end."