KatInterview

Find Unique Integer Triplets Summing to Target

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingarraystwo-pointerssorting

Last updated

Finds all unique value triplets in an integer array that sum to a specified target using sorting, two-pointer scanning, and pruning.

Given an array of integers a and a target integer k, return all unique value triplets [x, y, z] from a such that x + y + z == k.

The output must satisfy the following requirements:

  1. Each individual triplet [x, y, z] must be sorted in non-decreasing order (x <= y <= z).
  2. The overall list of triplets must be sorted in lexicographical order.
  3. No duplicate triplets should be returned.

Constraints

  • $0 \le \text{len}(a) \le 200,000$
  • $-10^9 \le a[i] \le 10^9$
  • $-10^9 \le k \le 10^9$

Examples

Example 1

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

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

Example 2

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

Output: [[0, 0, 0]]

Example 3

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

Output: []

Example 4

Input: find_triplets_with_sum([3, -1, -7, 5, 2, -4], 1)

Output: [[-7, 3, 5], [-4, 2, 3]]

Hints

Hint 1

Start by sorting the array. Sorting enables both two-pointer scanning and early pruning.

Hint 2

Fix the first element of the triplet, then use two pointers starting at the suffix boundaries to search for pairs.

Hint 3

Skip duplicate values for both the outer loop index and the two pointers after a valid match to avoid duplicate triplets.