Neutral Charge Trios

Mediumtwo pointersAlso known as 3Sum

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

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 written smallest first. No others: -3, for example, needs 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: 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

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