Triplet SumLoading saved progress…

Triplet Sum

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.

Signature

// 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.

Examples

// 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]]

Notes

  • Unique triplets only. If the same three values (as a sorted triple) can be formed more than once from different positions, include them once. [-1, -1, 2] appears a single time in the output regardless of how many -1s are in the input.
  • Dedup is about values, not indices. Two triplets are "the same" when their sorted value lists are equal. You are NOT just deduping index combinations — you are deduping the resulting value-triples.
  • Sorted output, both levels. Each triplet ascending, and the outer list ascending by first element, then second, then third. Tests compare against this exact shape, so order matters.
  • Fewer than three elements → return []. There is no triplet to form.
  • The target parameter is optional and defaults to 0, but it must work for any number (negative, positive, or zero).
  • Don't worry about returning indices, counting triplets instead of listing them, or k-sum for general k — those are out of scope (see Going further in the solution).
Loading editor…