KatInterview

Identify Unique Zero-Sum Triples

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searcharraystwo-pointerssorting

Last updated

Find all distinct combinations of three elements in an integer sequence that sum to zero using two pointers and duplicate handling.

Given an array of integers a, identify all unique groups of three elements whose sum equals 0.

Each triple must consist of values from three distinct indices in a. If duplicate numbers appear in different positions, they may be combined, but the output must contain no duplicate value triples.

Rules & Formatting

  • Each individual triple must be sorted in non-decreasing order: $[x, y, z]$ where $x \le y \le z$.
  • The output list of triples must be sorted in lexicographical order.
  • If no valid triples exist, return an empty list [].

Constraints

  • 0 <= len(a) <= 3000
  • -1000000 <= a[i] <= 1000000

Examples

Example 1

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

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

Example 2

Input: find_zero_sum_triplets([0, 0, 0, 0])

Output: [[0, 0, 0]]

Example 3

Input: find_zero_sum_triplets([])

Output: []

Example 4

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

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

Hints

Hint 1

Sorting the array beforehand allows you to iterate through the first element and solve the remaining subproblem using two pointers.

Hint 2

To avoid returning identical triples, skip duplicate values for the first element as well as subsequent pointers after a match is found.

Hint 3

If the fixed first element is strictly greater than 0 in a sorted array, can any three elements sum to zero?