Open In App

Count triplets such that sum of any two number is equal to third

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
Explanation: In the given array, there are two such triplets such that sum of the two numbers is equal to the third number, those are (1, 2, 3), (3, 2, 5)
 

Input: arr[] = [3, 2, 7]
Output:
Explanation: In the given array there are no such triplets such that sum of two numbers is equal to the third number.  

We have already discussed, how to check if there is a triplet such that sum of two is equal to the third. In this article, we are going to focus on approaches to count triplets.

[Naive Approach] Generating all triplets - O(n ^ 3) time and O(1) space

Generate all the triplets of the given array and check the sum of two elements to equal the third element.

C++
#include <iostream>
#include<vector>
using namespace std;

int cntTriplets(vector<int>&arr, int n)
{
    int count = 0;

    // Loop to count for triplets
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {

            for (int k = j + 1; k < n; k++) {
                if (arr[i] + arr[j] == arr[k]) {
                    count++;
                }
                else if (arr[i] + arr[k] == arr[j]) {
                    count++;
                }
                else if (arr[j] + arr[k] == arr[i]) {
                    count++;
                }
            }
        }
    }
    return count;
}

int main()
{
    int n = 4;
    vector<int> arr = { 1, 5, 3, 2 };

    cout << cntTriplets(arr, n);
    return 0;
}
Java
import java.util.List;
import java.util.ArrayList;

public class GfG{
    public static int cntTriplets(List<Integer> arr, int n) {
        int count = 0;

        // Loop to count for triplets
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if (arr.get(i) + arr.get(j) == arr.get(k)) {
                        count++;
                    } else if (arr.get(i) + arr.get(k) == arr.get(j)) {
                        count++;
                    } else if (arr.get(j) + arr.get(k) == arr.get(i)) {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int n = 4;
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(5);
        arr.add(3);
        arr.add(2);

        System.out.println(cntTriplets(arr, n));
    }
}
Python
def cntTriplets(arr, n):
    count = 0

    # Loop to count for triplets
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if arr[i] + arr[j] == arr[k]:
                    count += 1
                elif arr[i] + arr[k] == arr[j]:
                    count += 1
                elif arr[j] + arr[k] == arr[i]:
                    count += 1
    return count

n = 4
arr = [1, 5, 3, 2]

print(cntTriplets(arr, n))
C#
using System;
using System.Collections.Generic;

class Program {
    public static int cntTriplets(List<int> arr, int n) {
        int count = 0;

        // Loop to count for triplets
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    if (arr[i] + arr[j] == arr[k]) {
                        count++;
                    } else if (arr[i] + arr[k] == arr[j]) {
                        count++;
                    } else if (arr[j] + arr[k] == arr[i]) {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    static void Main() {
        int n = 4;
        List<int> arr = new List<int> { 1, 5, 3, 2 };

        Console.WriteLine(cntTriplets(arr, n));
    }
}
JavaScript
function cntTriplets(arr, n) {
    let count = 0;

    // Loop to count for triplets
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            for (let k = j + 1; k < n; k++) {
                if (arr[i] + arr[j] === arr[k]) {
                    count++;
                } else if (arr[i] + arr[k] === arr[j]) {
                    count++;
                } else if (arr[j] + arr[k] === arr[i]) {
                    count++;
                }
            }
        }
    }
    return count;
}

const n = 4;
const arr = [1, 5, 3, 2];

console.log(cntTriplets(arr, n));

Output
2

[Expected Approach] Using Hash Set - O(n ^ 2) time and O(n) space

The idea is to using a frequency Hash Map or Dictionary to store the count of each element in the array. Then, it iterates over all pairs of elements (arr[i], arr[j]) and checks if their sum exists in the array using the frequency map.

Algorithm:

  • Declare a Hash Set to store all numbers.
  • Run two loops to choose two different indexes of the matrix and check if the sum of the elements at those indices is present in t or not.
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

int cntTriplets(vector<int>& arr) {
    int n = arr.size();
    unordered_set<int> s;

    // Add all elements to set
    for (int i = 0; i < n; i++) {
        s.insert(arr[i]);
    }

    int count = 0;

    // Check for each pair if their sum exists 
    // in the set
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];
            
            // If sum is present. Please note that
            // this works because the question says
            // all elements are distinct
            if (s.find(sum) != s.end()) {
                count++;
            }
        }
    }

    return count;
}

int main() {
    vector<int> arr = {1, 5, 3, 2};
    cout << cntTriplets(arr);
    return 0;
}
Java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static int cntTriplets(int[] arr) {
        int n = arr.length;
        Set<Integer> s = new HashSet<>();

        // Add all elements to set
        for (int i = 0; i < n; i++) {
            s.add(arr[i]);
        }

        int count = 0;

        // Check for each pair if their sum exists 
        // in the set
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
                
                // If sum is present. Please note that
                // this works because the question says
                // all elements are distinct
                if (s.contains(sum)) {
                    count++;
                }
            }
        }

        return count;
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 3, 2};
        System.out.println(cntTriplets(arr));
    }
}
Python
def cnt_triplets(arr):
    n = len(arr)
    s = set()

    # Add all elements to set
    for i in range(n):
        s.add(arr[i])

    count = 0

    # Check for each pair if their sum exists 
    # in the set
    for i in range(n):
        for j in range(i + 1, n):
            sum_ = arr[i] + arr[j]
            
            # If sum is present. Please note that
            # this works because the question says
            # all elements are distinct
            if sum_ in s:
                count += 1

    return count

arr = [1, 5, 3, 2]
print(cnt_triplets(arr))
C#
using System;
using System.Collections.Generic;

class Program {
    public static int CntTriplets(int[] arr) {
        int n = arr.Length;
        HashSet<int> s = new HashSet<int>();

        // Add all elements to set
        for (int i = 0; i < n; i++) {
            s.Add(arr[i]);
        }

        int count = 0;

        // Check for each pair if their sum exists 
        // in the set
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
                
                // If sum is present. Please note that
                // this works because the question says
                // all elements are distinct
                if (s.Contains(sum)) {
                    count++;
                }
            }
        }

        return count;
    }

    static void Main() {
        int[] arr = {1, 5, 3, 2};
        Console.WriteLine(CntTriplets(arr));
    }
}
JavaScript
function cntTriplets(arr) {
    const n = arr.length;
    const s = new Set();

    // Add all elements to set
    for (let i = 0; i < n; i++) {
        s.add(arr[i]);
    }

    let count = 0;

    // Check for each pair if their sum exists 
    // in the set
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            const sum = arr[i] + arr[j];
            
            // If sum is present. Please note that
            // this works because the question says
            // all elements are distinct
            if (s.has(sum)) {
                count++;
            }
        }
    }

    return count;
}

const arr = [1, 5, 3, 2];
console.log(cntTriplets(arr));

Output
2



Next Article
Article Tags :
Practice Tags :

Similar Reads