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

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 elementint 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 Codeint 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 elementpublic 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 Codepublic 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 elementdef 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 Codeif __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 elementusing 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 elementfunction 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)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



