Skip to content
Preptima
mediumCodingEntryMidSenior

Return every distinct triplet in the array that sums to zero.

4 min readUpdated 2026-08-15

Answer

Short answer

Sort the array, fix each element as an anchor, then converge two pointers inwards from both ends of the remaining range. The sort is asymptotically free against the O of n squared scan, and it is what lets you skip duplicate values positionally instead of deduplicating a set of results afterwards.

Was this answer helpful?

Likely follow-ups

  • Generalise this to k-sum. What is the recurrence for the running time?
  • The target is now an arbitrary value rather than zero. Which of your optimisations survive?
  • Solve it with hashing instead. Why is deduplication harder that way?
  • Find the triplet whose sum is closest to the target rather than equal to it.

Related questions