Find Unique Combination Triples for Target Sum
Heaps, Sorting & SearchAuto-graded · 22 test casesLast 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
aand $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: []
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for unique value combinations $[x, y, z]$ drawn from distinct indices of an array such that $x \le y \le z$ and $x + y + z = k$.
-
Sort a copy of the input: Sorting takes $O(n \log n)$ time and allows us to use the two-pointer strategy. It guarantees that any triple found in index order $(i, \text{left}, \text{right})$ with $i < \text{left} < \text{right}$ is already non-decreasing ($arr[i] \le arr[\text{left}] \le arr[\text{right}]$).
-
Iterate the first element: Loop index $i$ from $0$ up to $n-3$. To avoid processing duplicate value triples starting with the same value, if $i > 0$ and $arr[i] == arr[i-1]$, we skip index $i$.
-
Two-pointer scan for the second and third elements: For a fixed $arr[i]$, initialize two pointers
left = i + 1andright = n - 1. Calculatecurrent_sum = arr[i] + arr[left] + arr[right]:- If
current_sum < k, incrementleftto increase the sum. - If
current_sum > k, decrementrightto decrease the sum. - If
current_sum == k, append[arr[i], arr[left], arr[right]]to our result. To prevent duplicate output triples, advanceleftpast all identical elements and retreatrightpast all identical elements.
- If
Because the outer loop processes $arr[i]$ in sorted order and the two pointers generate $arr[\text{left}]$ in increasing order, the result triples are naturally constructed in lexicographical order.
Complexity Analysis
- Time Complexity: $O(n^2 + P)$, where $n$ is the length of
aand $P$ is the total number of output triples. Sorting takes $O(n \log n)$ time. The outer loop runs $O(n)$ times, and the inner two-pointer pass takes $O(n)$ steps. Appending and advancing past duplicates takes time proportional to $P$. - Space Complexity: $O(n + P)$ auxiliary space to store the sorted copy of
aof size $n$ and the result list of $P$ triples.
Python Reference Solution
from typing import List
def three_sum_target(a: List[int], k: int) -> List[List[int]]:
arr = sorted(a)
n = len(arr)
ans = []
for i in range(n - 2):
if i > 0 and arr[i] == arr[i - 1]:
continue
left = i + 1
right = n - 1
while left < right:
current_sum = arr[i] + arr[left] + arr[right]
if current_sum < k:
left += 1
elif current_sum > k:
right -= 1
else:
ans.append([arr[i], arr[left], arr[right]])
val_left = arr[left]
val_right = arr[right]
while left < right and arr[left] == val_left:
left += 1
while left < right and arr[right] == val_right:
right -= 1
return ans