3Sum
All unique triplets that sum to zero.
Problem
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] with i, j, and k all different, such that nums[i] + nums[j] + nums[k] = 0.
- Triplets must be unique - no duplicates in the result.
- Order inside a triplet does not matter.
- Order of the result does not matter.
Examples
Approach
- Sort the array so equal values sit together and sums move predictably.
- Fix nums[i] as the first number. Skip it if it equals nums[i - 1], and stop once nums[i] > 0 - nothing after it can bring the sum back to 0.
- Put L just after i and R at the end. If the sum is too small, move L right; if too big, move R left.
- On a match, record the triplet, then move L and R past any repeated values before continuing, so the same triplet is not recorded twice.
Brute force: Three loops inside each other, plus a set to throw away repeated triplets. On 1,000 numbers that is a billion steps.
Common mistakes
- Skipping duplicates only for i is not enough: after a match, repeated values at L or R produce the same triplet again - e.g. [-2, 0, 0, 2, 2].
- Deduplicating afterwards with JSON.stringify works, but hides the real fix and costs extra memory.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned