![]() |
VOOZH | about |
Given an array arr[], and an integer target, find all possible unique triplets in the array whose sum is equal to the given target value. We can return triplets in any order, but all the returned triplets should be internally sorted, i.e., for any triplet [q1, q2, q3], the condition q1 ≤ q2 ≤ q3 should hold.
Examples:
Input: arr[] = [12, 3, 6, 1, 6, 9], target = 24
Output: [[3, 9, 12], [6, 6, 12]]
Explanation: There are two unique triplets that add up to 24:
3 + 9 + 12 = 24
6 + 6 + 12 = 24
Input: arr[] = [-2, 0, 1, 1, 2], target = 10
Output: []
Explanation: There is not triplet with sum 10.
Table of Content
We use three nested loops to generate all possible triplets, then check if their sum is equal to the target. If it is, we run an additional loop to check if the triplet is already in the result; if not, we add it.
3 9 12 6 6 12
The idea is to maintain a hash set to track whether a particular element occurred in the array so far or not. As we traverse all pairs using two nested loops, for each pair {arr[i], arr[j]}, we check if the complement (target - arr[i] - arr[j]) is already in the set. If it is, we have found a triplet whose sum equals the target. Each valid triplet is inserted into ta hash set to avoid duplicates.
3 9 12 6 6 12
The idea is to sort the array and use two pointers technique to find all the triplets. We will traverse the array and fix the first element of the triplet then, Initialize two pointers at the beginning and end of the remaining array. Now, compare the sum of elements at these pointers:
- If sum = target, store the triplet and skip duplicates to ensure they are distinct.
- If sum < target, we move the left pointer towards right.
- If sum > target, we move the right pointer towards left.
3 9 12 6 6 12