3 Sum - Count all triplets with given sum
Last Updated : 28 Dec, 2024
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.
C++ // C++ program to count all triplets having sum equal to // target by exploring all possible triplets #include <iostream> #include <vector> using namespace std; int countTriplets(vector<int> &arr, int target) { int cnt = 0; int n = arr.size(); // Generating all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // If the sum of a triplet is equal to target // then increment count by 1 if (arr[i] + arr[j] + arr[k] == target) cnt += 1; } } } return cnt; } int main() { vector<int> arr = {0, -1, 2, -3, 1}; int target = -2; cout << countTriplets(arr, target); return 0; }
C // C program to count all triplets having sum equal to // target by exploring all possible triplets #include <stdio.h> int countTriplets(int arr[], int n, int target) { int cnt = 0; // Generating all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // If the sum of a triplet is equal to target // then increment count by 1 if (arr[i] + arr[j] + arr[k] == target) cnt += 1; } } } return cnt; } int main() { int arr[] = {0, -1, 2, -3, 1}; int target = -2; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n", countTriplets(arr, n, target)); return 0; }
Java // Java program to count all triplets having sum equal to // target by exploring all possible triplets import java.util.Arrays; class GfG { // Function to count all triplets having sum equal to target static int countTriplets(int[] arr, int target) { int cnt = 0; int n = arr.length; // Generating all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // If the sum of a triplet is equal to target // then increment count by 1 if (arr[i] + arr[j] + arr[k] == target) cnt += 1; } } } return cnt; } public static void main(String[] args) { int[] arr = {0, -1, 2, -3, 1}; int target = -2; System.out.println(countTriplets(arr, target)); } }
Python # Python program to count all triplets having sum equal to # target by exploring all possible triplets def countTriplets(arr, target): cnt = 0 n = len(arr) # Generating all triplets for i in range(n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): # If the sum of a triplet is equal to target # then increment count by 1 if arr[i] + arr[j] + arr[k] == target: cnt += 1 return cnt if __name__ == "__main__": arr = [0, -1, 2, -3, 1] target = -2 print(countTriplets(arr, target))
C# // C# program to count all triplets having sum equal to // target by exploring all possible triplets using System; class GfG { // Function to count all triplets having sum equal to target static int countTriplets(int[] arr, int target) { int cnt = 0; int n = arr.Length; // Generating all triplets for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { // If the sum of a triplet is equal to target // then increment count by 1 if (arr[i] + arr[j] + arr[k] == target) cnt += 1; } } } return cnt; } static void Main() { int[] arr = { 0, -1, 2, -3, 1 }; int target = -2; Console.WriteLine(countTriplets(arr, target)); } }
JavaScript // JavaScript program to count all triplets having sum equal to // target by exploring all possible triplets // Function to count all triplets having sum equal to target function countTriplets(arr, target) { let cnt = 0; let n = arr.length; // Generating all triplets for (let i = 0; i < n - 2; i++) { for (let j = i + 1; j < n - 1; j++) { for (let k = j + 1; k < n; k++) { // If the sum of a triplet is equal to target // then increment count by 1 if (arr[i] + arr[j] + arr[k] === target) cnt += 1; } } } return cnt; } // Example usage const arr = [0, -1, 2, -3, 1]; const target = -2; console.log(countTriplets(arr, target));
[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.
C++ // C++ program to count all triplets having sum equal to // target using Hash Set #include <iostream> #include <unordered_map> #include <vector> using namespace std; // Returns number of pairs in arr[idx..n-1] with sum equal // to 'target' int getPairsCount(vector<int> &arr, int idx, int target) { unordered_map<int, int> freq; int count = 0; for (int i = idx; i < arr.size(); i++) { // Check if the complement (target - arr[i]) // exists in the map. If yes, increment count if (freq.find(target - arr[i]) != freq.end()) { count += freq[target - arr[i]]; } // Increment the frequency of arr[i] freq[arr[i]]++; } return count; } // Returns count of triplets with sum = target int countTriplets(vector<int> &arr, int target) { int cnt = 0; int n = arr.size(); // Iterating over the first element of the triplet for (int i = 0; i < n - 2; i++) { int rem = target - arr[i]; cnt += getPairsCount(arr, i + 1, rem); } return cnt; } int main() { vector<int> arr = {0, -1, 2, -3, 1}; int target = -2; cout << countTriplets(arr, target); return 0; }
Java // Java program to count all triplets having sum equal to // target using Hash Set import java.util.HashMap; import java.util.Map; class GfG { // Returns number of pairs in arr[idx..n-1] with sum equal // to 'target' static int getPairsCount(int[] arr, int idx, int target) { Map<Integer, Integer> freq = new HashMap<>(); int count = 0; for (int i = idx; i < arr.length; i++) { // Check if the complement (target - arr[i]) // exists in the map. If yes, increment count if (freq.containsKey(target - arr[i])) { count += freq.get(target - arr[i]); } // Increment the frequency of arr[i] freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1); } return count; } // Returns count of triplets with sum = target static int countTriplets(int[] arr, int target) { int cnt = 0; int n = arr.length; // Iterating over the first element of the triplet for (int i = 0; i < n - 2; i++) { int rem = target - arr[i]; cnt += getPairsCount(arr, i + 1, rem); } return cnt; } public static void main(String[] args) { int[] arr = {0, -1, 2, -3, 1}; int target = -2; System.out.println(countTriplets(arr, target)); } }
Python # Python program to count all triplets having sum equal to # target using Hash Set def getPairsCount(arr, idx, target): freq = {} count = 0 for i in range(idx, len(arr)): # Check if the complement (target - arr[i]) # exists in the map. If yes, increment count if target - arr[i] in freq: count += freq[target - arr[i]] # Increment the frequency of arr[i] freq[arr[i]] = freq.get(arr[i], 0) + 1 return count # Returns count of triplets with sum = target def countTriplets(arr, target): cnt = 0 n = len(arr) # Iterating over the first element of the triplet for i in range(n - 2): rem = target - arr[i] cnt += getPairsCount(arr, i + 1, rem) return cnt if __name__ == "__main__": arr = [0, -1, 2, -3, 1] target = -2 print(countTriplets(arr, target))
C# // C# program to count all triplets having sum equal to // target using Hash Set using System; using System.Collections.Generic; class GfG { // Returns number of pairs in arr[idx..n-1] with sum equal // to 'target' static int GetPairsCount(int[] arr, int idx, int target) { Dictionary<int, int> freq = new Dictionary<int, int>(); int count = 0; for (int i = idx; i < arr.Length; i++) { // Check if the complement (target - arr[i]) // exists in the map. If yes, increment count if (freq.ContainsKey(target - arr[i])) { count += freq[target - arr[i]]; } // Increment the frequency of arr[i] if (freq.ContainsKey(arr[i])) freq[arr[i]]++; else freq[arr[i]] = 1; } return count; } // Returns count of triplets with sum = target static int CountTriplets(int[] arr, int target) { int cnt = 0; int n = arr.Length; // Iterating over the first element of the triplet for (int i = 0; i < n - 2; i++) { int rem = target - arr[i]; cnt += GetPairsCount(arr, i + 1, rem); } return cnt; } static void Main() { int[] arr = { 0, -1, 2, -3, 1 }; int target = -2; Console.WriteLine(CountTriplets(arr, target)); } }
JavaScript // JavaScript program to count all triplets having sum equal to // target using Hash Set function getPairsCount(arr, idx, target) { const freq = {}; let count = 0; for (let i = idx; i < arr.length; i++) { // Check if the complement (target - arr[i]) // exists in the map. If yes, increment count if (freq[target - arr[i]] !== undefined) { count += freq[target - arr[i]]; } // Increment the frequency of arr[i] freq[arr[i]] = (freq[arr[i]] || 0) + 1; } return count; } // Returns count of triplets with sum = target function countTriplets(arr, target) { let cnt = 0; const n = arr.length; // Iterating over the first element of the triplet for (let i = 0; i < n - 2; i++) { const rem = target - arr[i]; cnt += getPairsCount(arr, i + 1, rem); } return cnt; } const arr = [0, -1, 2, -3, 1]; const target = -2; console.log(countTriplets(arr, target));
We have discussed one more approach, that works for sorted arrays, in the post 3 Sum - Count Triplets With Given Sum In Sorted Array.
Similar Reads
3 Sum - Find all Triplets with Given Sum Given an array arr[] and an integer target, the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to given target and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted o
12 min read
3 Sum - Count Triplets With Given Sum In Sorted Array Given a sorted 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. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k.Examp
10 min read
3 Sum - Find All Triplets with Zero Sum Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k.Ex
11 min read
3 Sum â All Distinct Triplets with given Sum in an Array 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 sho
15+ min read
Count triplets with sum smaller than a given value Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input :
11 min read