Ledger Entries That Cancel Out

Medium · Two Pointers · about 25 min

An accountant has a list of ledger entries (whole numbers: positive for money in, negative for money out). She wants every way to pick three entries at three different positions that add up to exactly 0.

Return the distinct trios of values:

  • each trio is a list sorted ascending, like [-1, -1, 2];
  • no trio appears twice (two trios are the same if they hold the same three values);
  • the list of trios is sorted ascending (compare the first values, then the second, then the third).

Return [] when there is none. Do not change the input list.

Example:

zero_trios([-1, 0, 1, 2, -1, -4]) → [[-1, -1, 2], [-1, 0, 1]]

Hints

  • Sort a copy of the entries so you can reason about "too small" and "too big".
  • Fix the first value of the trio, then look for two more values to its right that cancel it, using one pointer from each end.
  • To avoid repeats, skip a first value equal to the one just before it, and after a match move the left pointer past every copy of its value.

Learn the pattern first: the Two Pointers lesson.

More Two Pointers problems