Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Count of elements which is the sum of a subarray of the given Array
Next article icon

Count of triplets from the given Array such that sum of any two elements is the third element

Last Updated : 03 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array arr, the task is to find the count of the distinct triplets in which the sum of any two elements is the third element.

Examples:  

Input: arr[] = {1, 3, 4, 15, 19} 
Output: 2 
Explanation: 
In the given array there are two triplets such that the sum of the two elements is equal to the third element: {{1, 3, 4}, {4, 15, 19}}

Input: arr[] = {7, 2, 5, 4, 3, 6, 1, 9, 10, 12} 
Output: 18 

Approach:  

  • Sort the given array
  • Create a Hash map for the array to check that a particular element is present or not.
  • Iterate over the Array with two Loops to select any two elements at different positions and check that the sum of those two elements is present in the hash map in O(1) time.
  • If the sum of the two elements is present in the hash map, then increment the count of the triplets.

Below is the implementation of the above approach:  

C++




// C++ Implementation to find the
// Count the triplets in which sum
// of two elements is the third element
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find the count
// the triplets in which sum
// of two elements is the third element
int triplets(vector<int>arr)
{
 
    // Dictionary to check a element is
    // present or not in array
    map<int, int> k;
    map<pair<int, int>, int> mpp;
 
    // List to check for
    // duplicates of Triplets
    vector<vector<int >> ssd;
 
    // Set initial count to zero
    int count = 0;
 
    // Sort the array
    sort(arr.begin(),arr.end());
 
    int i = 0;
    while (i < arr.size())
    {
 
        // Add all the values as key
        // value pairs to the dictionary
        if (k.find(arr[i]) == k.end())
            k[arr[i]] = 1;
 
        i += 1;
    }
 
    // Loop to choose two elements
    int j = 0;
    while (j < arr.size() - 1)
    {
 
        int q = j + 1;
        while (q < arr.size())
        {
 
            // Check for the sum and duplicate
            if ( k.find(arr[j] + arr[q]) != k.end() and
                mpp[{arr[j], arr[q]}] != arr[j] + arr[q])
            {
 
                count += 1;
 
                ssd.push_back({arr[j], arr[q], arr[j] + arr[q]});
                mpp[{arr[j], arr[q]}] = arr[j] + arr[q];
            }
 
            q += 1;
        }
        j += 1;
    }
    return count;
}
 
 
// Driver Code
int main()
{
    vector<int>arr = {7, 2, 5, 4, 3, 6, 1, 9, 10, 12};
    int count = triplets(arr);
    printf("%d",count);
    return 0;
}
 
// This code is contributed by mohit kumar 29
 
 

Java




// Java implementation to find the
// Count the triplets in which sum
// of two elements is the third element
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
 
class GFG{
     
// Function to find the count the triplets
// in which sum of two elements is the third element
public static int triplets(ArrayList<Integer> arr)
{
     
      // Dictionary to check a element is
       // present or not in array
    HashSet<Integer> k = new HashSet<>();
     
      // List to check for
    // duplicates of Triplets
    HashSet<ArrayList<Integer>> ssd = new HashSet<>();
 
      // Set initial count to zero
    int count = 0;
   
    // Sort the array
    Collections.sort(arr);
 
    int i = 0;
 
      // Add all the values as key
    // value pairs to the dictionary
    while (i < arr.size())
    {
        if (!k.contains(arr.get(i)))
        {
            k.add(arr.get(i));
        }
        i += 1;
    }
    int j = 0;
     
    // Loop to choose two elements
    while (j < arr.size() - 1)
    {
        int q = j + 1;
         
          // Check for the sum and duplicate
        while (q < arr.size())
        {
            ArrayList<Integer> trip = new ArrayList<>();
            trip.add(arr.get(j));
            trip.add(arr.get(q));
            trip.add(arr.get(j) + arr.get(q));
             
            if (k.contains(arr.get(j) + arr.get(q)) &&
                !ssd.contains(trip))
            {
                count += 1;
                ArrayList<Integer> nums = new ArrayList<>();
                nums.add(arr.get(j));
                nums.add(arr.get(q));
                nums.add(arr.get(j) + arr.get(q));
                ssd.add(nums);
            }
            q += 1;
        }
        j += 1;
    }
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    ArrayList<Integer> arr = new ArrayList<>();
    arr.add(7);
    arr.add(2);
    arr.add(5);
    arr.add(4);
    arr.add(3);
    arr.add(6);
    arr.add(1);
    arr.add(9);
    arr.add(10);
    arr.add(12);
     
    int count = triplets(arr);
     
    System.out.println(count);
}
}
 
// This code is contributed by aditya7409
 
 

Python3




# Python3 Implementation to find the
# Count the triplets in which sum
# of two elements is the third element
 
# Function to find the count
# the triplets in which sum
# of two elements is the third element
def triplets(arr):
 
    # Dictionary to check a element is
    # present or not in array
    k = set()
     
    # List to check for
    # duplicates of Triplets
    ssd = []
     
    # Set initial count to zero
    count = 0
 
    # Sort the array
    arr.sort()
 
    i = 0
    while i < len(arr):
         
        # Add all the values as key
        # value pairs to the dictionary
        if arr[i] not in k:
            k.add(arr[i])
 
        i += 1
 
    # Loop to choose two elements
    j = 0
    while j < len(arr) - 1:
 
        q = j + 1
        while q < len(arr):
 
            # Check for the sum and duplicate
            if arr[j] + arr[q] in k and\
               [arr[j], arr[q], arr[j] + arr[q]] not in ssd:
 
                count += 1
 
                ssd.append([arr[j], arr[q], arr[j] + arr[q]])
 
            q += 1
        j += 1
 
    return count
 
 
# Driver Code
if __name__ == "__main__":
    arr = [7, 2, 5, 4, 3, 6, 1, 9, 10, 12]
    count = triplets(arr)
    print(count)
 
 

C#




// C# Implementation to find the
// Count the triplets in which sum
// of two elements is the third element
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to find the count
  // the triplets in which sum
  // of two elements is the third element
  static int triplets(List<int> arr)
  {
 
    // Dictionary to check a element is
    // present or not in array
    Dictionary<int, int> k = new Dictionary<int, int>();
    Dictionary<Tuple<int, int>, int> mpp = new Dictionary<Tuple<int, int>, int>();
 
    // List to check for
    // duplicates of Triplets
    List<List<int>> ssd = new List<List<int>>();
 
    // Set initial count to zero
    int count = 0;
 
    // Sort the array
    arr.Sort();
 
    int i = 0;
    while (i < arr.Count)
    {
 
      // Add all the values as key
      // value pairs to the dictionary
      if (!k.ContainsKey(arr[i]))
        k[arr[i]] = 1;
 
      i += 1;
    }
 
    // Loop to choose two elements
    int j = 0;
    while (j < arr.Count - 1)
    {
      int q = j + 1;
      while (q < arr.Count)
      {
 
        // Check for the sum and duplicate
        if(!k.ContainsKey(arr[j] + arr[q]))
        {
          q += 1;
          continue;
        }
        if (mpp.ContainsKey(new Tuple<int,int>(arr[j], arr[q])) &&
            mpp[new Tuple<int,int>(arr[j], arr[q])] != (arr[j] + arr[q]))
        {
          count += 1;   
          ssd.Add(new List<int>(new int[]{arr[j], arr[q], arr[j] + arr[q]}));
          mpp[new Tuple<int,int>(arr[j], arr[q])] = arr[j] + arr[q];
        }
        else{
          count += 1;
          ssd.Add(new List<int>(new int[]{arr[j], arr[q], arr[j] + arr[q]}));
          mpp[new Tuple<int,int>(arr[j], arr[q])] = arr[j] + arr[q];
        }    
        q += 1;
      }
      j += 1;
    }
    return count;
  }
 
  // Driver code
  static void Main()
  {
    List<int> arr = new List<int>(new int[]{7, 2, 5, 4, 3, 6, 1, 9, 10, 12});
    int count = triplets(arr);
    Console.Write(count);
  }
}
 
// This code is contributed by divyeshrabadiya07
 
 

Javascript




<script>
// Javascript implementation to find the
// Count the triplets in which sum
// of two elements is the third element
       
// Function to find the count the triplets
// in which sum of two elements is the third element
function triplets(arr)
{
      
    // Dictionary to check a element is
    // present or not in array
    let k = new Set();
      
    // List to check for
    // duplicates of Triplets
    let ssd = new Set();
  
    // Set initial count to zero
    let count = 0;
    
    // Sort the array
    arr.sort((a, b) => a - b);
  
    let i = 0;
  
      // Add all the values as key
    // value pairs to the dictionary
    while (i < arr.length)
    {
        if (!k.has(arr[i]))
        {
            k.add(arr[i]);
        }
        i += 1;
    }
    let j = 0;
      
    // Loop to choose two elements
    while (j < arr.length - 1)
    {
        let q = j + 1;
          
        // Check for the sum and duplicate
        while (q < arr.length)
        {
            let trip = new Array();
            trip.push(arr[j]);
            trip.push(arr[q]);
            trip.push(arr[j] + arr[q]);
              
            if (k.has(arr[j] + arr[q]) &&
                !ssd.has(trip))
            {
                count += 1;
                let nums = new Array();
                nums.push(arr[j]);
                nums.push(arr[q]);
                nums.push(arr[j] + arr[q]);
                ssd.add(nums);
            }
            q += 1;
        }
        j += 1;
    }
    return count;
}
  
// Driver Code
 
    let arr = new Array();
    arr.push(7);
    arr.push(2);
    arr.push(5);
    arr.push(4);
    arr.push(3);
    arr.push(6);
    arr.push(1);
    arr.push(9);
    arr.push(10);
    arr.push(12);
      
    let count = triplets(arr);
      
    document.write(count);
 
 
// This code is contributed by gfgking
</script>
 
 
Output: 
18

 

Time Complexity: O(N2*logN)

Auxiliary Space: O(3*N2)



Next Article
Count of elements which is the sum of a subarray of the given Array
author
akash_c
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • Hash
  • Technical Scripter
  • Technical Scripter 2019
Practice Tags :
  • Algorithms
  • Arrays
  • Hash

Similar Reads

  • Find three element from given three arrays such that their sum is X | Set 2
    Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A
    9 min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Count triplets such that sum of any two number is equal to third
    Given an array of distinct positive integers arr[] of length n, the task is to count all the triplets such that the sum of two elements equals the third element. Examples: Input: arr[] = [1, 5, 3, 2] Output: 2 Explanation: In the given array, there are two such triplets such that sum of the two numb
    7 min read
  • Find a triplet such that sum of two equals to third element
    Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element. Examples: Input: arr[] = [1, 2, 3, 4, 5]Output: TrueExplanation: The pair (1, 2) sums to 3. Input: arr[] = [3, 4, 5]Output: TrueExplanation: No triplets satisfy the condition. Input
    14 min read
  • Count of all triplets such that XOR of two equals to third element
    Given an array arr[] of positive integers, the task is to find the count of all triplets such that XOR of two equals the third element. In other words count all the triplets (i, j, k) such that arr[i] ^ arr[j] = arr[k] and i < j < k. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1Explanation: O
    6 min read
  • Find three element from different three arrays such that a + b + c = sum
    Given three integer arrays and a "sum", the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays. Examples : Input : a1[] = { 1 , 2 , 3 , 4 , 5 }; a2[] = { 2 , 3 , 6 , 1 , 2 }; a3[] = { 3 , 2 , 4 , 5 , 6 }; sum = 9 Output : Ye
    15+ min read
  • Javascript Program to Find a triplet such that sum of two equals to third element
    Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element. Examples: Input: {5, 32, 1, 7, 10, 50, 19, 21, 2}Output: 21, 2, 19Input: {5, 32, 1, 7, 10, 50, 19, 21, 0}Output: no such triplet existQuestion source: Arcesium Interview Experience
    3 min read
  • Count of triplets of numbers 1 to N such that middle element is always largest
    Given an integer N, the task is to count the number of ways to arrange triplets (a, b, c) within [1, N] in such a way such that the middle element is always greater than left and right elements. Example: Input: N = 4 Output: 8 Explanation For the given input N = 4 number of possible triplets are:{1,
    4 min read
  • Count triplets from a given range having sum of two numbers of a triplet equal to the third number
    Given two integers L and R, the task is to find the number of unique triplets whose values lie in the range [L, R], such that the sum of any two numbers is equal to the third number. Examples: Input: L = 1, R = 3Output: 3Explanation: Three such triplets satisfying the necessary conditions are (1, 1,
    9 min read
  • Count Triplets such that one of the numbers can be written as sum of the other two
    Given an array A[] of N integers. The task is to find the number of triples (i, j, k) , where i, j, k are indices and (1 <= i < j < k <= N), such that in the set { [Tex]A_i [/Tex], [Tex]A_j [/Tex], [Tex]A_k [/Tex]} at least one of the numbers can be written as the sum of the other two.Ex
    10 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