![]() |
VOOZH | about |
Given an array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target.
Examples:
Input: arr[] = [0, -1, 2, -3, 1], target = -2
Output: 2
Explanation: Two triplets that add up to -2 are:
arr[0] + arr[3] + arr[4] = 0 + (-3) + (1) = -2
arr[1] + arr[2] + arr[3] = (-1) + 2 + (-3) = -2
Input: arr[] = [1, -2, 1, 0, 5], target = 1
Output: 0
Explanation: There is no triplet whose sum is equal to 1.
Table of Content
The naive approach is to explore all the triplets using three nested loops and if the sum of any triplet is equal to given target then increment the counter by 1.
2
The idea is to iterate over the array and fix the first element of the triplet as arr[i]. For the remaining two elements, we simply use the logic of counting pairs using Hash Set for the subarray arr[i+1 ... n-1] and sum as (target - arr[i]).
2
We have discussed one more approach, that works for sorted arrays, in the post 3 Sum - Count Triplets With Given Sum In Sorted Array.