Python coding

Triplets that cancel out

Given a list of integers nums, return every distinct triplet of values [a, b, c], taken from three different positions, with a + b + c == 0. Two triplets are the same if they hold the same values, so each must appear only once. The order of the triplets, and of the values inside each one, does not matter.

Aim for O(n²) time instead of checking every triple in O(n³).

Besides the tests, one large input (400 numbers, many repeats) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

  • zero_triplets([-1,0,1,2,-1,-4]) → [[-1,-1,2],[-1,0,1]]
  • zero_triplets([0,1,1]) → []
  • zero_triplets([0,0,0]) → [[0,0,0]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort first. Fix the smallest value a[i]; the other two must sum to -a[i], a pair sum on the sorted rest.

Hint 2

Run lo and hi from both ends of a[i+1:]: sum too small, move lo right; too big, move hi left.

Hint 3

To avoid repeats, skip an i equal to its left neighbor, and after a hit move lo past equal values.

Solution and why it works
pythonO(n²) · O(n) for the sorted copy, output aside
def zero_triplets(nums: list[int]) -> list[list[int]]:
    a = sorted(nums)
    found = []
    for i in range(len(a) - 2):
        if i > 0 and a[i] == a[i - 1]:
            continue
        lo, hi = i + 1, len(a) - 1
        while lo < hi:
            s = a[i] + a[lo] + a[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                found.append([a[i], a[lo], a[hi]])
                lo, hi = lo + 1, hi - 1
                while lo < hi and a[lo] == a[lo - 1]:
                    lo += 1
    return found

Sorting lets you fix a[i] and solve the rest as a pair sum from both ends: each move of lo or hi discards candidates for good, so O(n) per i and O(n²) overall, versus O(n³) brute force. The trap is duplicates: skip an i equal to its left neighbor, and after a hit step lo past equal values, or the same triplet appears several times.

Related lab: Loops in motion