Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
3 Sum - Count all triplets with given sum
Next article icon

3 Sum - Count all triplets with given sum

Last Updated : 28 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • [Naive Approach] Explore all Triplets – O(n^3) Time and O(1) Space
  • [Expected Approach 1] Using Hash Set - O(n^2) Time and O(n) Space

[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)); 

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

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.



Next Article
3 Sum - Count all triplets with given sum

M

mrityuanjay8vae
Improve
Article Tags :
  • Hash
  • DSA
  • Arrays
  • 3Sum
Practice Tags :
  • Arrays
  • Hash

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences