VOOZH about

URL: https://www.geeksforgeeks.org/dsa/3-sum-count-all-triplets-with-given-sum/

⇱ 3 Sum - Count all triplets with given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

3 Sum - Count all triplets with given sum

Last Updated : 23 Jul, 2025

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.

[Naive Approach] Explore all Triplets – O(n^3) Time and O(1) Space

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.


Output
2

[Expected Approach 1] Using Hash Set - O(n^2) Time and O(n) Space

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]).

  • Initialize the counter count with 0 to store the number of triplets.
  • Traverse the given array over the range [0, n – 2) using the variable i. For each element arr[i]:
    • Find the value of the remaining sum(say rem) as (target – arr[i]).
    • Call the method discussed in counting pairs for the subarray from i+1 to end of the array and add the returned value to count.
  • After the above steps, print the value of count as the result.

Output
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.


Comment
Article Tags:
Article Tags: