Skip to content
BytePatterns

Three Values Summing to Zero

MediumArrays#two-pointers#sort-first#skip-duplicates~30m

Problem

A ledger audit looks for three entries that cancel out exactly. Given a list of integers nums, return every distinct triplet [a, b, c] of values taken from three different positions with a + b + c = 0. Write each triplet in ascending order and list the triplets in ascending order; two triplets with the same values count once. The list has up to 3,000 values, so trying every triple is too slow.

Examples

Input:  nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Why:    the two -1 values can both be used, but [-1, 0, 1] is listed once
Input:  nums = [0, 1, 1]
Output: []
Input:  nums = [0, 0, 0, 0]
Output: [[0, 0, 0]]
Why:    edge case, four zeros still give just one distinct triplet

Hints

0 / 3

Stuck on the idea rather than the code? Two Pointers covers it.