Three to zero
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
Given a list of whole numbers nums, find every set of three numbers from different positions that adds up to exactly 0.
Return a list of these triples. Each triple should appear only once: [-1, 0, 1] and [0, 1, -1] count as the same triple, so return just one of them.
The triples, and the numbers inside each triple, can be in any order.
Examples
Example 1
- Input
- nums = [4, -2, 1, -2, 0, -1, 3]
- Output
- [[-2, -2, 4], [-2, -1, 3], [-1, 0, 1]]
-2 + -2 + 4, -2 + -1 + 3 and -1 + 0 + 1 all make 0. The two -2s are at different positions, so both can be used.
Example 2
- Input
- nums = [0, 0, 0, 0]
- Output
- [[0, 0, 0]]
Many ways to pick three zeros, but they all make the same triple.
Example 3
- Input
- nums = [1, 2, 3]
- Output
- []
No three numbers add up to 0.
Rules
numshas between 0 and 3,000 numbers, from -100,000 to 100,000.- The same value can appear more than once in
nums, and can then be used more than once in a triple.
Words on this page, in plain English (2)Open if any word is new to you
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
We want all the different triples that add up to 0, not just one. Two things make it tricky:
- The same value can appear more than once, and each copy can be used:
[-1, -1, 2]is fine if there are two-1s. - But each triple must only be listed once:
[-1, 0, 1]and[0, -1, 1]are the same triple.
2. Solve an example by hand
[4, -2, 1, -2, 0, -1, 3]. Pick a first number, say -2. Now you need two others that add up to 2: -2 + 4 works (the other -2), and so does -1 + 3. Then pick -1 as the first number: you need two that add up to 1: 0 + 1 works. Then 0 as the first number: you need -1 + 1, but that's [-1, 0, 1] again.
So the problem is really "fix one number, then find pairs", and the hard part is not repeating yourself.
3. The slow way
Three nested loops try every triple, saving each one sorted (as a string key in a Set) to avoid repeats. That's O(n³): about 4.5 billion triples for 3,000 numbers. Too slow.
4. Spot the pattern
After fixing the first number a, we're looking for a pair that adds up to -a. That's exactly Pair in a sorted list, if the list is sorted. So: sort first, then two pointers for each first number.
Sorting also solves the repeats problem: equal values sit next to each other, so we can skip a value that's the same as the one before it.
5. The idea
- Sort the numbers.
- For each position
i, unlesssorted[i]equals the previous first number: - Run two pointers on everything after
i, looking for a sum of 0. - When a triple is found, save it, move both pointers, and skip over repeats of the middle number.
Fix one number, squeeze for the other two
sorted
- sum =
- –
- triples =
- []
function threeToZero(nums) { const sorted = [...nums].sort((a, b) => a - b); const triples = []; for (let i = 0; i < sorted.length - 2; i++) { if (i > 0 && sorted[i] === sorted[i - 1]) { continue; // same first number as last time } let left = i + 1; let right = sorted.length - 1; while (left < right) { const sum = sorted[i] + sorted[left] + sorted[right]; if (sum < 0) { left++; } else if (sum > 0) { right--; } else { triples.push([sorted[i], sorted[left], sorted[right]]); left++; right--; while (left < right && sorted[left] === sorted[left - 1]) { left++; // skip repeats of the middle number } } } } return triples;}Sort first: [-2, -2, -1, 0, 1, 3, 4]. Now equal numbers sit together, and two pointers can work.
6. The code, line by line
const sorted = [...nums].sort((a, b) => a - b); const triples = [];Sort a copy (not the caller's list).
(a, b) => a - bsorts numbers by size; without it, JavaScript sorts them like words, and10comes before9.for (let i = 0; i < sorted.length - 2; i++) { if (i > 0 && sorted[i] === sorted[i - 1]) { continue; // same first number as last time }Each position is a possible first number. Stop 2 before the end, because two more numbers are needed after it. Skip a value we've already used as the first number.
let left = i + 1; let right = sorted.length - 1; while (left < right) { const sum = sorted[i] + sorted[left] + sorted[right]; if (sum < 0) { left++; } else if (sum > 0) { right--;Pair in a sorted list, on the part after
i. Too small: moveleftup. Too big: moverightdown.} else { triples.push([sorted[i], sorted[left], sorted[right]]); left++; right--;A triple! Save it and move both pointers inward.
while (left < right && sorted[left] === sorted[left - 1]) { left++; // skip repeats of the middle number }Skip repeats of the middle number, or the same triple would be found again. (Repeats of the last number take care of themselves: the sum will be wrong until
rightpasses them.)
7. How fast is it?
| Every triple | Sort + two pointers | |
|---|---|---|
| Time | O(n³) | O(n²): n first numbers × an O(n) squeeze |
| Extra memory | O(answers) | O(n) for the sorted copy |
The sort costs O(n log n), which is smaller than O(n²), so it doesn't change the total.
Common mistakes
- Sorting numbers without a compare function.
[10, 9, 1].sort()gives[1, 10, 9]. Always use.sort((a, b) => a - b)for numbers. - Skipping repeats too early. Skip a repeated first number only after it has been used once (
i > 0 && sorted[i] === sorted[i - 1]), or[-1, -1, 2]is lost. - Stopping after the first triple. There can be many; keep squeezing after a match.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Three to zero
Read the 27 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function threeToZero(nums) { const sorted = [...nums].sort((a, b) => a - b); const triples = []; for (let i = 0; i < sorted.length - 2; i++) { if (i > 0 && sorted[i] === sorted[i - 1]) { continue; // same first number as last time } let left = i + 1; let right = sorted.length - 1; while (left < right) { const sum = sorted[i] + sorted[left] + sorted[right]; if (sum < 0) { left++; } else if (sum > 0) { right--; } else { triples.push([sorted[i], sorted[left], sorted[right]]); left++; right--; while (left < right && sorted[left] === sorted[left - 1]) { left++; // skip repeats of the middle number } } } } return triples;}