KatInterview

Find Unique Combination Triples for Target Sum

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searcharrayssortingtwo-pointers

Last updated

Find all distinct non-decreasing 3-element value combinations in an array that add up to a specified target value.

Given an array of integers a and an integer k, find all unique non-decreasing triples of values [x, y, z] chosen from three distinct indices in a such that x + y + z == k.

Every unique combination of values [x, y, z] with x <= y <= z must appear exactly once in the returned list, regardless of how many identical elements appear in a. The list of triples should be returned in lexicographical order.

The original input array a must not be modified. If no three indices satisfy the requirement, return an empty list.

Constraints

  • 0 <= len(a) <= 2000
  • -1,000,000,000 <= a[i], k <= 1,000,000,000
  • The runtime complexity should be within $O(n^2 + P)$, where $n$ is the length of a and $P$ is the number of resulting triples.

Examples

Example 1

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

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

Example 2

Input: three_sum_target([2, 2, 2, 2], 6)

Output: [[2, 2, 2]]

Example 3

Input: three_sum_target([1, 2], 3)

Output: []