Neutral Charge Trios
A school chemistry lab has a shelf of vials, each labelled with its electric charge as a whole number, like -3, 0 or 2. An experiment needs mixtures of exactly three vials whose charges add up to 0.
The teacher wants every possible charge combination listed. Vials with the same label are interchangeable, so [-1, 0, 1] is listed once, however many ways the shelf can make it.
Your task
Write neutralTrios(charges). Return every distinct trio of values [a, b, c] with a + b + c = 0, taken from three different vials (three different positions in charges).
Write each trio in ascending order (a ≤ b ≤ c). Trios can be returned in any order, but none may appear twice. If there are none, return an empty list.
neutralTrios(charges: int[]) → int[][] Any order of the returned list is accepted.
Examples
charges = [2, -3, 0, 1, -1, -2]
[[-3, 1, 2], [-2, 0, 2], [-1, 0, 1]]
Three trios add up to 0: -3 + 1 + 2, -2 + 0 + 2 and -1 + 0 + 1, each written smallest first. No others: -3, for example, needs two vials summing to 3, and only 1 + 2 works.
charges = [0, 0, 0, 0]
[[0, 0, 0]]
Any three of the four zero vials work: 4 choices of vials, but the same charges. List [0, 0, 0] once.
Constraints
- 0 ≤ charges.length ≤ 3,000
- -100,000 ≤ charges[i] ≤ 100,000
Start with brute force
Try every combination of three positions with three nested loops, keep those summing to 0, sort each trio and put it in a set to remove repeats.
3,000 vials give about 4.5 billion combinations. The waste is the innermost loop: once two values are chosen the third is fixed, so searching for it one by one is pointless.
Hints
0 of 4 shown- Hint 1
Suppose the trio must include the -3 vial. What must the other two add up to? Have you solved that smaller question before?
- Hint 2
Fixing one value leaves a smaller problem: find two values that add up to a target. On a sorted list, two pointers from the ends do that in one pass.
- Hint 3
Sort the charges. For each position
i, look for pairs to its right adding up to-charges[i]. Looking only right means each trio is found once, from its smallest value. - Hint 4
In the pair search: if the sum is too small move
leftright, if too big moverightleft, if exact record it and move both. To avoid duplicates, skip aniequal to the previous value, and after a match keep movingleftwhile it repeats the value just used.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Sort first. Pick the trio's smallest member, a[i]; the question becomes "which two values to its right add up to -a[i]?" On a sorted list that is a two-pointer search from both ends.
Trace [2, -3, 0, 1, -1, -2], sorted to [-3, -2, -1, 0, 1, 2]:
i= 0 (-3). The pair must sum to 3. Withlefton -2 andrighton 2 the total is -3, which is too small, soleftmoves right. The totals for -1 and 2, then 0 and 2, are -2 and -1, soleftkeeps moving. The pair 1 and 2 gives 0, so[-3, 1, 2]is recorded and the pointers cross.i= 1 (-2). The pair -1 and 2 totals -1, soleftmoves right. The pair 0 and 2 totals 0, so[-2, 0, 2]is recorded, and thenleftandrightmeet and the search stops.i= 2 (-1). The pair 0 and 2 totals 1, which is too big, sorightmoves left. The pair 0 and 1 totals 0, so[-1, 0, 1]is recorded.i= 3 (0). The pair 1 and 2 totals 3, which is too big, sorightmoves left and the pointers meet. Later starts leave fewer than three values, so the loop ends.
Sorting puts duplicates together: skip an i with the same value as the one before, and after a match slide left past copies of the value just used. Both rules stop a trio being recorded twice.
function neutralTrios(charges) {
const a = [...charges].sort((x, y) => x - y);
const result = [];
for (let i = 0; i < a.length - 2; i++) {
if (a[i] > 0) break; // three positives cannot sum to 0
if (i > 0 && a[i] === a[i - 1]) continue; // same smallest value as before
let left = i + 1, right = a.length - 1;
while (left < right) {
const sum = a[i] + a[left] + a[right];
if (sum < 0) left++;
else if (sum > 0) right--;
else {
result.push([a[i], a[left], a[right]]);
left++;
right--;
while (left < right && a[left] === a[left - 1]) left++; // skip repeats
}
}
}
return result;
}def neutral_trios(charges):
a = sorted(charges)
result = []
for i in range(len(a) - 2):
if a[i] > 0:
break # three positives cannot sum to 0
if i > 0 and a[i] == a[i - 1]:
continue # same smallest value as before
left, right = i + 1, len(a) - 1
while left < right:
s = a[i] + a[left] + a[right]
if s < 0:
left += 1
elif s > 0:
right -= 1
else:
result.append([a[i], a[left], a[right]])
left += 1
right -= 1
while left < right and a[left] == a[left - 1]:
left += 1 # skip repeats
return resultRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.