3Sum
The rite of passage: find every unique triplet summing to zero without drowning in duplicates or O(n³). Sort once, fix one element, and let two pointers squeeze the rest — the pattern that generalizes to a whole family of k-sum problems.
The problem
Given nums, return all unique triplets [a, b, c] with a + b + c = 0. Each triplet must be sorted ascending, the list of triplets sorted lexicographically, and no triplet may appear twice — even if the input contains duplicates.
nums = [-1, 0, 1, 2, -1, -4][[-1, -1, 2], [-1, 0, 1]]nums = [0, 0, 0, 0][[0, 0, 0]]nums = [1, 2, 3][]- Triplets sorted ascending internally; the result list sorted lexicographically.
- No duplicate triplets in the output.
- Target O(n²): sort + fixed element + two pointers, not three nested loops.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement three_sum(nums) → all unique zero-sum triplets, using sort + two pointers and duplicate-skipping at every level.
- Sort first. Sorted order is what makes both the two pointers AND the dedup possible.
- Fix index i; find pairs in nums[i+1:] summing to -nums[i] with left/right pointers.
- Sum too small → move left up; too big → move right down; equal → record and move BOTH.
- Skip duplicates three times: at i, at left after a hit, at right after a hit.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.