Find All Triplets That Sum to a Target Value
Arrays & HashingAuto-graded · 23 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The optimal strategy combines sorting with a two-pointer scan. First, sort the input array so that elements are arranged in ascending order. Then, iterate through the array and treat each element as the potential first element of a triplet. For each fixed first element, use two pointers to find pairs in the remaining portion that complete the target sum.
How the two-pointer scan works:
- Place one pointer (
left) immediately after the current first element - Place another pointer (
right) at the end of the array - Calculate the sum of the three elements
- If the sum matches the target, record the triplet and move both pointers inward
- If the sum is too small, advance the left pointer to increase the sum
- If the sum is too large, move the right pointer backward to decrease the sum
Avoiding duplicates:
- Skip over consecutive identical values when selecting the first element
- After finding a match, advance both pointers past any duplicate values to prevent recording the same triplet multiple times
Because the array is sorted and we maintain i < left < right, every triplet automatically satisfies the non-decreasing order requirement, and the output naturally emerges in lexicographic order.
Why It Works
Every valid triplet will be discovered exactly once. When we process the first occurrence of a value as the anchor, the two-pointer sweep examines all possible pairs in the sorted suffix without missing any valid combinations. The pointer movements are exhaustive: moving left right when the sum is too small is safe because pairing that element with any smaller right would only make the sum even smaller. Similarly, moving right left when the sum is too large is safe for the symmetric reason.
Duplicate elimination is precise: skipping duplicate anchors avoids reprocessing the same first element, and skipping duplicate left or right values after a match ensures each distinct triplet is recorded only once.
Complexity
Time: O(n²)
- Sorting takes O(n log n)
- The outer loop runs n times, and for each iteration the two-pointer scan takes O(n) in total (each pointer moves at most n positions across all iterations)
- Overall: O(n log n + n²) = O(n²)
Space: O(1) auxiliary space beyond the output
- The algorithm uses only a constant number of variables (pointers and indices)
- Sorting modifies the input array in place (or uses O(n) space for a copy, depending on implementation)
- The output can contain up to O(n²) triplets in the worst case, but this is the result size, not working memory
from typing import List
def find_triplets_with_sum(nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = []
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == target:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < target:
left += 1
else:
right -= 1
return result