KatInterview

Zero-Sum Triplets in an Array

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingarray-traversal

Last updated

Tests two-pointer technique on sorted arrays, duplicate avoidance, and quadratic complexity optimization for finding triplet combinations.

Problem

Write a function that accepts an array of integers and returns every distinct triplet of values from the array that sums to zero.

Each triplet should contain three values from three different positions in the input array. The output must not contain duplicate triplets—if two triplets contain the same three values, include only one of them.

You may return the triplets in any order, and each triplet's values may appear in any order.

Input

  • numbers: a list of integers

Output

  • A list of lists, where each inner list contains exactly three integers whose sum equals zero
  • No two triplets in the output should contain the same set of three values

Constraints

  • 0 ≤ len(numbers) ≤ 3000
  • -100000 ≤ numbers[i] ≤ 100000

Examples

Example 1

Input: find_zero_sum_triplets([-1, 0, 1, 2, -1, -4])

Output: [[-1, -1, 2], [-1, 0, 1]]

Hints

Hint 1

Sorting the array first allows you to efficiently search for pairs that complement a fixed anchor value.

Hint 2

Once sorted, use two pointers moving from opposite ends to find pairs that sum to a target in linear time.

Hint 3

Skip over consecutive duplicate values during iteration to prevent generating the same triplet multiple times.