Given an array of numbers, find every unique group of three values that add up to a target. This is the classic 3Sum problem — a staple interview question because the obvious answer is a slow triple loop, and the good answer teaches a reusable trick: sort the array, then sweep it with two pointers. The hard part is not the arithmetic, it's returning each distinct triplet exactly once even when the input is full of duplicates.
// nums: number[] — the input array (may contain duplicates, may be empty)
// target: number — the sum each triplet must hit; defaults to 0
// returns: number[][]
// Every UNIQUE triplet [a, b, c] of values taken from THREE DIFFERENT
// positions in nums, where a + b + c === target.
// Output convention (so the result is deterministic):
// - each triplet is sorted ascending: a <= b <= c
// - the list of triplets is sorted ascending too (by a, then b, then c)
function tripletSum(nums: number[], target?: number): number[][];
A triplet uses three distinct positions, but those positions may hold equal values — [0, 0, 0] is a valid triplet if three different slots all hold 0.
// The classic case. target defaults to 0.
tripletSum([-1, 0, 1, 2, -1, -4]);
// → [[-1, -1, 2], [-1, 0, 1]]
// Note: only TWO triplets, even though -1 appears twice — the duplicate
// pairing [-1, 0, 1] is not repeated.
// No three values sum to the target → empty array.
tripletSum([1, 2, 3, 4], 100); // → []
// A non-zero target, with the result still sorted both ways.
tripletSum([1, 1, 2, 3, 4], 6); // → [[1, 1, 4], [1, 2, 3]]
[-1, -1, 2] appears a single time in the output regardless of how many -1s are in the input.[]. There is no triplet to form.target parameter is optional and defaults to 0, but it must work for any number (negative, positive, or zero).k — those are out of scope (see Going further in the solution).