Open In App

Count Triplets such that one of the numbers can be written as sum of the other two

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 { A_i     A_j     A_k     } at least one of the numbers can be written as the sum of the other two.
Examples
 

Input : A[] = {1, 2, 3, 4, 5}
Output : 4
The valid triplets are:
(1, 2, 3), (1, 3, 4), (1, 4, 5), (2, 3, 5)

Input : A[] = {1, 1, 1, 2, 2}
Output : 6


 


This is a counting problem. Let’s say f(x) represents the frequency of number x     in our array.
There exist four cases: 
 

  1. All three numbers are equal to 0. The number of ways = f(0)C3 (where pCq is the number of ways of choosing q numbers from p numbers).
  2. One number is equal to 0, the other two are equal to some x > 0: f(0) * f(x)C2.
  3. Two numbers are equal to some x>0, the third is 2*x: f(x)C2 * f(2 * x).
  4. The three numbers are x, y and x + y, 0 < x, y: f(x) * f(y) * f(x + y).


Below is the implementation of the above approach: 
 

C++

// C++ program to count Triplets such that at
// least one of the numbers can be written
// as sum of the other two
#include<bits/stdc++.h>
using namespace std;
 
    // Function to count the number of ways
    // to choose the triples
    int countWays(int arr[], int n)
    {
        // compute the max value in the array
        // and create frequency array of size
        // max_val + 1.
        // We can also use HashMap to store
        // frequencies. We have used an array
        // to keep remaining code simple.
        int max_val = 0;
        for (int i = 0; i < n; i++)
            max_val = max(max_val, arr[i]);
        int freq[max_val + 1]={0};
        for (int i = 0; i < n; i++)
            freq[arr[i]]++;
 
        int ans = 0; // stores the number of ways
 
        // Case 1: 0, 0, 0
        ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6;
 
        // Case 2: 0, x, x
        for (int i = 1; i <= max_val; i++)
            ans += freq[0] * freq[i] * (freq[i] - 1) / 2;
 
        // Case 3: x, x, 2*x
        for (int i = 1; 2 * i <= max_val; i++)
            ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i];
 
        // Case 4: x, y, x + y
        // iterate through all pairs (x, y)
        for (int i = 1; i <= max_val; i++) {
            for (int j = i + 1; i + j <= max_val; j++)
                ans += freq[i] * freq[j] * freq[i + j];
        }
 
        return ans;
    }
 
    // Driver code
    int main()
    {
        int arr[]={ 1, 2, 3, 4, 5 };
        int n = sizeof(arr)/sizeof(int);
        cout<<(countWays(arr, n));
        return 0;
    }
 
//contributed by Arnab Kundu

                    

Java

// Java program to count Triplets such that at
// least one of the numbers can be written
// as a sum of the other two
 
class GFG {
 
    // Function to count the number of ways
    // to choose the triples
    static int countWays(int[] arr, int n)
    {
        // compute the max value in the array
        // and create frequency array of size
        // max_val + 1.
        // We can also use HashMap to store
        // frequencies. We have used an array
        // to keep remaining code simple.
        int max_val = 0;
        for (int i = 0; i < n; i++)
            max_val = Math.max(max_val, arr[i]);
        int[] freq = new int[max_val + 1];
        for (int i = 0; i < n; i++)
            freq[arr[i]]++;
 
        int ans = 0; // stores the number of ways
 
        // Case 1: 0, 0, 0
        ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6;
 
        // Case 2: 0, x, x
        for (int i = 1; i <= max_val; i++)
            ans += freq[0] * freq[i] * (freq[i] - 1) / 2;
 
        // Case 3: x, x, 2*x
        for (int i = 1; 2 * i <= max_val; i++)
            ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i];
 
        // Case 4: x, y, x + y
        // iterate through all pairs (x, y)
        for (int i = 1; i <= max_val; i++) {
            for (int j = i + 1; i + j <= max_val; j++)
                ans += freq[i] * freq[j] * freq[i + j];
        }
 
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5 };
        int n = arr.length;
        System.out.println(countWays(arr, n));
    }
}

                    

Python3

# Python3 program to count Triplets such
# that at least one of the numbers can be
# written as sum of the other two
import math as mt
 
# Function to count the number of ways
# to choose the triples
def countWays(arr, n):
 
    # compute the max value in the array
    # and create frequency array of size
    # max_val + 1.
    # We can also use HashMap to store
    # frequencies. We have used an array
    # to keep remaining code simple.
    max_val = 0
    for i in range(n):
        max_val = max(max_val, arr[i])
 
    freq = [0 for i in range(max_val + 1)]
 
    for i in range(n):
        freq[arr[i]] += 1
 
    ans = 0 # stores the number of ways
 
    # Case 1: 0, 0, 0
    ans += (freq[0] * (freq[0] - 1) *
           (freq[0] - 2) // 6)
 
    # Case 2: 0, x, x
    for i in range(1, max_val + 1):
        ans += (freq[0] * freq[i] *
               (freq[i] - 1) // 2)
 
    # Case 3: x, x, 2*x
    for i in range(1, (max_val + 1) // 2):
        ans += (freq[i] *
               (freq[i] - 1) // 2 * freq[2 * i])
 
    # Case 4: x, y, x + y
    # iterate through all pairs (x, y)
    for i in range(1, max_val + 1):
        for j in range(i + 1, max_val - i + 1):
            ans += freq[i] * freq[j] * freq[i + j]
 
    return ans
 
# Driver code
arr = [ 1, 2, 3, 4, 5]
n = len(arr)
print(countWays(arr, n))
 
# This code is contributed by
# mohit kumar 29

                    

C#

// C# program to count Triplets
// such that at least one of the
// numbers can be written as sum
// of the other two
using System;
 
class GFG
{
 
// Function to count the number
// of ways to choose the triples
static int countWays(int[] arr, int n)
{
    // compute the max value in the array
    // and create frequency array of size
    // max_val + 1.
    // We can also use HashMap to store
    // frequencies. We have used an array
    // to keep remaining code simple.
    int max_val = 0;
    for (int i = 0; i < n; i++)
        max_val = Math.Max(max_val, arr[i]);
         
    int[] freq = new int[max_val + 1];
    for (int i = 0; i < n; i++)
        freq[arr[i]]++;
 
    int ans = 0; // stores the number of ways
 
    // Case 1: 0, 0, 0
    ans += freq[0] * (freq[0] - 1) *
                     (freq[0] - 2) / 6;
 
    // Case 2: 0, x, x
    for (int i = 1; i <= max_val; i++)
        ans += freq[0] * freq[i] *
                        (freq[i] - 1) / 2;
 
    // Case 3: x, x, 2*x
    for (int i = 1;
             2 * i <= max_val; i++)
        ans += freq[i] * (freq[i] - 1) /
                      2 * freq[2 * i];
 
    // Case 4: x, y, x + y
    // iterate through all pairs (x, y)
    for (int i = 1; i <= max_val; i++)
    {
        for (int j = i + 1;
                 i + j <= max_val; j++)
            ans += freq[i] * freq[j] *
                             freq[i + j];
    }
 
    return ans;
}
 
// Driver code
public static void Main()
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int n = arr.Length;
    Console.WriteLine(countWays(arr, n));
}
}
 
// This code is contributed by shs..

                    

Javascript

<script>
 
// JavaScript program to count Triplets such that at
// least one of the numbers can be written
// as a sum of the other two   
     
    // Function to count the number of ways
    // to choose the triples
    function countWays(arr,n)
    {
        // compute the max value in the array
        // and create frequency array of size
        // max_val + 1.
        // We can also use HashMap to store
        // frequencies. We have used an array
        // to keep remaining code simple.
        let max_val = 0;
        for (let i = 0; i < n; i++)
            max_val = Math.max(max_val, arr[i]);
        let freq = new Array(max_val + 1);
        for(let i=0;i<freq.length;i++)
        {
            freq[i]=0;
        }
        for (let i = 0; i < n; i++)
            freq[arr[i]]++;
   
        let ans = 0; // stores the number of ways
   
        // Case 1: 0, 0, 0
        ans += freq[0] * (freq[0] - 1) * (freq[0] - 2) / 6;
   
        // Case 2: 0, x, x
        for (let i = 1; i <= max_val; i++)
            ans += freq[0] * freq[i] * (freq[i] - 1) / 2;
   
        // Case 3: x, x, 2*x
        for (let i = 1; 2 * i <= max_val; i++)
            ans += freq[i] * (freq[i] - 1) / 2 * freq[2 * i];
   
        // Case 4: x, y, x + y
        // iterate through all pairs (x, y)
        for (let i = 1; i <= max_val; i++) {
            for (let j = i + 1; i + j <= max_val; j++)
                ans += freq[i] * freq[j] * freq[i + j];
        }
   
        return ans;
    }
     
    // Driver code
    let arr=[1, 2, 3, 4, 5];
    let n = arr.length;
    document.write(countWays(arr, n));
 
     
 
// This code is contributed by patel2127
 
</script>

                    

PHP

<?php
// PHP program to count Triplets such that at
// least one of the numbers can be written
// as sum of the other two
 
// Function to count the number of ways
// to choose the triples
function countWays($arr, $n)
{
    // compute the max value in the array
    // and create frequency array of size
    // max_val + 1.
    // We can also use HashMap to store
    // frequencies. We have used an array
    // to keep remaining code simple.
    $max_val = 0;
    for ($i = 0; $i < $n; $i++)
        $max_val = max($max_val, $arr[$i]);
    $freq = array_fill(0, $max_val + 1, 0);
    for ($i = 0; $i < $n; $i++)
        $freq[$arr[$i]]++;
 
    $ans = 0; // stores the number of ways
 
    // Case 1: 0, 0, 0
    $ans += (int)($freq[0] * ($freq[0] - 1) *
                             ($freq[0] - 2) / 6);
 
    // Case 2: 0, x, x
    for ($i = 1; $i <= $max_val; $i++)
        $ans += (int)($freq[0] * $freq[$i] *
                     ($freq[$i] - 1) / 2);
 
    // Case 3: x, x, 2*x
    for ($i = 1; 2 * $i <= $max_val; $i++)
        $ans += (int)($freq[$i] * ($freq[$i] - 1) / 2 *
                                   $freq[2 * $i]);
 
    // Case 4: x, y, x + y
    // iterate through all pairs (x, y)
    for ($i = 1; $i <= $max_val; $i++)
    {
        for ($j = $i + 1; $i + $j <= $max_val; $j++)
            $ans += $freq[$i] * $freq[$j] *
                                $freq[$i + $j];
    }
 
    return $ans;
}
 
// Driver code
$arr = array( 1, 2, 3, 4, 5 );
$n = count($arr);
echo countWays($arr, $n);
 
// This code is contributed by mits
?>

                    

Output
4

Time complexity of the given C++ program is O(max_val^2 ), where max_val is the maximum value in the input array.

The space complexity of the program is O(max_val), as we are using an array of size max_val+1 to store the frequency of elements in the input array.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads