Problem 335759 · medium · Level 03 Linear Management & Searching

Trios That Cancel to Zero

two pointers · sorting · arrays

Fix one number, and "find three numbers that sum to zero" becomes "find two numbers that sum to a target" on the rest, which two pointers on a sorted list answer in one linear pass. Sorting first also makes duplicate triplets easy to skip.

A lab bench holds a row of charge readings nums, positive and negative integers. Find every way to pick three readings, from three different positions, that cancel out exactly: return all unique triplets [a, b, c] with a + b + c == 0. The triplets may come in any order, and so may the numbers inside each one, but no triplet may be listed twice.

Examples

Input:  nums = [3, -2, 1, -2, 0, 4, -1]
Output: [[-2, -2, 4], [-2, -1, 3], [-1, 0, 1]]
Input:  nums = [1, 2, -4]
Output: []
Input:  nums = [0, 0, 0, 0]
Output: [[0, 0, 0]]

Constraints

  • Aim for O(n²) time. The brute-force O(n³) triple loop with a set of tuples works on small inputs but is the wrong habit to build.

Goals

  • Reduce a three-element problem to a two-pointer search by fixing one element
  • Sort first so that duplicates are adjacent and can be skipped
  • Produce every unique triplet exactly once
Starting Python…