Find Unique Integer Triplets Summing to Target
Arrays & HashingAuto-graded · 24 test casesLast 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:
- Each individual triplet
[x, y, z]must be sorted in non-decreasing order (x <= y <= z). - The overall list of triplets must be sorted in lexicographical order.
- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires finding all unique triplets of values in an array a that sum to a target k. We can achieve this efficiently by combining array sorting with a two-pointer approach:
- Sorting & Outer Loop: First, sort the array in non-decreasing order. Iterate through the array with index
i, treatingvalues[i]as the candidate for the smallest value of the triplet. - Duplicate Skipping:
- For
i > 0, skipvalues[i]ifvalues[i] == values[i - 1]to ensure each distinct first value is processed only once. - After recording a matching triplet
[values[i], values[left], values[right]], incrementleftpast all identical elements and decrementrightpast all identical elements to prevent duplicate secondary/tertiary values.
- For
- Pruning Optimizations:
- If the sum of
values[i]and the next two smallest values (values[i + 1] + values[i + 2]) exceedsk, no valid triplets can start atior any later index, so we canbreakearly. - If the sum of
values[i]and the two largest values (values[n - 2] + values[n - 1]) is less thank,values[i]is too small to form a triplet with any values in the remaining suffix, so we cancontinueto the nexti.
- If the sum of
- Two Pointers:
- Set
left = i + 1andright = len(values) - 1. - Calculate
total = values[i] + values[left] + values[right]. - If
total < k, advanceleft. - If
total > k, retreatright. - If
total == k, record the triplet and advance both pointers past all identical values.
- Set
Complexity Analysis
- Time Complexity: $\mathcal{O}(n^2)$ where $n$ is the length of array
a. Sorting takes $\mathcal{O}(n \log n)$, and the nested two-pointer search runs at most $n$ inner operations for each of the $n$ outer iterations. - Space Complexity: $\mathcal{O}(n)$ auxiliary space to produce the sorted array (or $\mathcal{O}(1)$ beyond output if sorted in-place).
Python Source Code
from typing import List
def find_triplets_with_sum(a: List[int], k: int) -> List[List[int]]:
values = sorted(a)
n = len(values)
result = []
for i in range(n - 2):
if i > 0 and values[i] == values[i - 1]:
continue
if values[i] + values[i + 1] + values[i + 2] > k:
break
if values[i] + values[n - 2] + values[n - 1] < k:
continue
left, right = i + 1, n - 1
while left < right:
total = values[i] + values[left] + values[right]
if total < k:
left += 1
elif total > k:
right -= 1
else:
result.append([values[i], values[left], values[right]])
left_val, right_val = values[left], values[right]
while left < right and values[left] == left_val:
left += 1
while left < right and values[right] == right_val:
right -= 1
return result