KatInterview

Find All Triplets That Sum to a Target Value

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

Last updated

Tests efficient two-pointer technique with sorted arrays, duplicate handling, and edge-case reasoning.

You are given an array of integers nums and a target sum target.

Your task is to find all unique triplets of three elements from the array whose sum equals the target. Each triplet should be listed in non-decreasing order (first ≤ second ≤ third element), and the collection of triplets should be returned in lexicographic order.

Important: The same triplet must not appear more than once in the result, even if the array contains duplicate values.

Constraints

  • 0 ≤ len(nums) ≤ 3000
  • -10⁵ ≤ nums[i] ≤ 10⁵
  • -10⁵ ≤ target ≤ 10⁵
  • If the array has fewer than three elements, return an empty list
  • Each triplet may reuse a value only if that value appears multiple times in the array

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([1, 2, 3, 4, 5], 9)

Output: [[1, 3, 5], [2, 3, 4]]

Example 3

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

Output: [[0, 0, 0]]

Hints

Hint 1

Start by sorting the array. This enables efficient searching and makes it easier to avoid duplicates.

Hint 2

For each element as the first value, use two pointers on the remaining sorted portion to find pairs that complete the sum.

Hint 3

After finding a matching triplet, skip over duplicate values to ensure each triplet appears only once in the output.