Neutral Charge Trios

Mediumtwo pointersAlso known as 3Sum

A school chemistry lab has a shelf of vials. Each label shows the vial's electric charge as a whole number, like -3, 0 or 2. For an experiment the class needs mixtures made from exactly three vials whose charges add up to 0.

The teacher wants a list of every possible charge combination, so students can pick one. Two vials with the same label are interchangeable, so [-1, 0, 1] should be listed once, however many ways the shelf can make it.

Your task

Write neutralTrios(charges). Return every distinct trio of values [a, b, c] such that a + b + c = 0 and the three values come from three different vials (three different positions in charges).

Write each trio in ascending order (a ≤ b ≤ c). The trios themselves can be returned in any order. No trio may appear twice. If there are none, return an empty list.

neutralTrios(charges: int[]) → int[][] Any order of the returned list is accepted.

Examples

Example 1
Input
charges = [2, -3, 0, 1, -1, -2]
Output
[[-3, 1, 2], [-2, 0, 2], [-1, 0, 1]]
Why

Three trios add up to 0: -3 + 1 + 2, -2 + 0 + 2 and -1 + 0 + 1. Each is written smallest first. There are no others: for example -3 would need two vials summing to 3, and only 1 + 2 works.

Example 2
Input
charges = [0, 0, 0, 0]
Output
[[0, 0, 0]]
Why

Any three of the four zero vials work, which is 4 different choices of vials, but they all give 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 the ones that add up to 0, sort each trio and put it in a set to remove repeats.

With 3,000 vials there are about 4.5 billion combinations of three. That is far too many. The waste is in 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

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.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code