Back to Practice
#0232

Three Sum Triplets

MediumDSA28 min20 XP

Problem

Return all unique triplets [a, b, c] from nums such that a + b + c == 0. Each triplet must be sorted, and the final list must be sorted lexicographically.

Why This Matters

Three Sum teaches how sorting plus two pointers removes duplicate work without missing valid combinations.

Function Signature

def three_sum(nums):

Examples

Example 1
Inputnums = [-1, 0, 1, 2, -1, -4]
Output[[-1, -1, 2], [-1, 0, 1]]

Sorting lets us find pairs for each fixed first number and skip duplicate triplets.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Classic duplicate case
Input[-1, 0, 1, 2, -1, -4]
Expected[[-1, -1, 2], [-1, 0, 1]]

Two unique zero-sum triplets exist.

All zeros
Input[0, 0, 0, 0]
Expected[[0, 0, 0]]

Duplicate triplets collapse into one answer.

Hidden Test Categories
no tripletsmany repeated negativesalready sorted input