3Sum
Return all unique triplets that sum to zero. Each triplet sorted ascending; the list of triplets sorted ascending too. Example: [-1,0,1,2,-1,-4] => [[-1,-1,2],[-1,0,1]]
3Sum is Two Sum with a twist: sort first, then walk two pointers inward for each anchor. The real trick is skipping duplicates cleanly so your answer set stays unique. Nail that and you have a template for 4Sum and every k-sum that follows.
Examples
You write
three_sum(nums: List[int])
Example 1
- Input
- [-1,0,1,2,-1,-4]
- returns
- [[-1,-1,2],[-1,0,1]]
Example 2
- Input
- [0,1,1]
- returns
- []
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsTwo Pointers
I reach for it when
- The array is sorted, or you can sort it.
- You need a pair, a triple or a palindrome.
Say this before you type. Say what each pointer means and what a move to the left or right rules out.
All 26 Two Pointers problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.