Given two arrays arr1[] and arr2[]. The task is to find the total number of distinct pairs(formed by picking 1 element from arr1 and one element from arr2), such that both the elements of the pair have the sum of digits.
Note: Pairs occurring more than once must be counted only once.
Examples:
Input : arr1[] = {33, 41, 59, 1, 3}
        arr2[] = {3, 32, 51, 3}
Output : 3
Possible pairs are:
(33, 51), (41, 32), (3, 3)
Input : arr1[] = {1, 6, 4, 22}
        arr2[] = {1, 3, 24}
Output : 2
Possible pairs are:
(1, 1), (6, 24)
Approach:
- Run two nested loops to generate all possible pairs from the two arrays taking one element from arr1[] and one from arr2[].
- If sum of digits is equal, then insert the pair(a, b) into a set, in order to avoid duplicates where a is the smaller element and b is the larger one.
- Total pairs will be the size of the final set.
Below is the implementation of the above approach:
C++
| // C++ program to count total number of// pairs having elements with same// sum of digits#include <bits/stdc++.h>usingnamespacestd;// Function for returning// sum of digits of a numberintdigitSum(intn){    intsum = 0;    while(n > 0) {        sum += n % 10;        n = n / 10;    }    returnsum;}// Function to return the total pairs// of elements with equal sum of digitsinttotalPairs(intarr1[], intarr2[], intn, intm){    // set is used to avoid duplicate pairs    set<pair<int, int> > s;    for(inti = 0; i < n; i++) {        for(intj = 0; j < m; j++) {            // check sum of digits            // of both the elements            if(digitSum(arr1[i]) == digitSum(arr2[j])) {                if(arr1[i] < arr2[j])                    s.insert(make_pair(arr1[i], arr2[j]));                else                    s.insert(make_pair(arr2[j], arr1[i]));            }        }    }    // return size of the set    returns.size();}// Driver codeintmain(){    intarr1[] = { 100, 3, 7, 50 };    intarr2[] = { 5, 1, 10, 4 };    intn = sizeof(arr1) / sizeof(arr1[0]);    intm = sizeof(arr2) / sizeof(arr2[0]);    cout << totalPairs(arr1, arr2, n, m);    return0;} | 
Java
| // Java program to count total number of// pairs having elements with same// sum of digitsimportjava.util.*;classGFG {staticclasspair{     intfirst, second;     publicpair(intfirst, intsecond)     {         this.first = first;         this.second = second;     } }// Function for returning// sum of digits of a numberstaticintdigitSum(intn){    intsum = 0;    while(n > 0)    {        sum += n % 10;        n = n / 10;    }    returnsum;}// Function to return the total pairs// of elements with equal sum of digitsstaticinttotalPairs(intarr1[], intarr2[],                      intn, intm){    // set is used to avoid duplicate pairs    Set<pair> s = newHashSet<>();    for(inti = 0; i < n; i++)     {        for(intj = 0; j < m; j++)         {            // check sum of digits            // of both the elements            if(digitSum(arr1[i]) == digitSum(arr2[j]))            {                if(arr1[i] < arr2[j])                    s.add(newpair(arr1[i], arr2[j]));                else                    s.add(newpair(arr2[j], arr1[i]));            }        }    }    // return size of the set    returns.size();}// Driver codepublicstaticvoidmain(String[] args){    intarr1[] = { 100, 3, 7, 50};    intarr2[] = { 5, 1, 10, 4};    intn = arr1.length;    intm = arr2.length;    System.out.println(totalPairs(arr1, arr2, n, m));}} // This code is contributed by Rajput-Ji | 
Python3
| # Python3 program to count total number of # pairs having elements with same sum of digits # Function for returning # sum of digits of a number defdigitSum(n):      Sum=0    whilen > 0:          Sum+=n %10        n =n //10         returnSum# Function to return the total pairs # of elements with equal sum of digits deftotalPairs(arr1, arr2, n, m):     # set is used to avoid duplicate pairs     s =set()     fori inrange(0, n):          forj inrange(0, m):              # check sum of digits             # of both the elements             ifdigitSum(arr1[i]) ==digitSum(arr2[j]):                  ifarr1[i] < arr2[j]:                     s.add((arr1[i], arr2[j]))                 else:                    s.add((arr2[j], arr1[i]))                  # return size of the set     returnlen(s) # Driver code if__name__ =="__main__":     arr1 =[100, 3, 7, 50]      arr2 =[5, 1, 10, 4]     n =len(arr1)     m =len(arr2)     print(totalPairs(arr1, arr2, n, m))     # This code is contributed by Rituraj Jain | 
C#
| // C# program to count total number of// pairs having elements with same// sum of digitsusingSystem;usingSystem.Collections.Generic;classGFG {publicclasspair{     publicintfirst, second;     publicpair(intfirst, intsecond)     {         this.first = first;         this.second = second;     } }// Function for returning// sum of digits of a numberstaticintdigitSum(intn){    intsum = 0;    while(n > 0)    {        sum += n % 10;        n = n / 10;    }    returnsum;}// Function to return the total pairs// of elements with equal sum of digitsstaticinttotalPairs(int[]arr1, int[]arr2,                      intn, intm){    // set is used to avoid duplicate pairs    HashSet<pair> s = newHashSet<pair>();    for(inti = 0; i < n; i++)     {        for(intj = 0; j < m; j++)         {            // check sum of digits            // of both the elements            if(digitSum(arr1[i]) == digitSum(arr2[j]))            {                if(arr1[i] < arr2[j])                    s.Add(newpair(arr1[i], arr2[j]));                else                    s.Add(newpair(arr2[j], arr1[i]));            }        }    }    // return size of the set    returns.Count;}// Driver codepublicstaticvoidMain(String[] args){    int[]arr1 = { 100, 3, 7, 50 };    int[]arr2 = { 5, 1, 10, 4 };    intn = arr1.Length;    intm = arr2.Length;    Console.WriteLine(totalPairs(arr1, arr2, n, m));}}// This code is contributed by Princi Singh | 
Javascript
| <script>// Javascript program to count total number of// pairs having elements with same// sum of digits// Function for returning// sum of digits of a numberfunctiondigitSum(n){    varsum = 0;    while(n > 0) {        sum += n % 10;        n = parseInt(n / 10);    }    returnsum;}// Function to return the total pairs// of elements with equal sum of digitsfunctiontotalPairs(arr1, arr2, n, m){    // set is used to avoid duplicate pairs    vars = newSet();    for(vari = 0; i < n; i++) {        for(varj = 0; j < m; j++) {            // check sum of digits            // of both the elements            if(digitSum(arr1[i]) == digitSum(arr2[j])) {                if(arr1[i] < arr2[j])                    s.add([arr1[i], arr2[j]]);                else                    s.add([arr2[j], arr1[i]]);            }        }    }    // return size of the set    returns.size;}// Driver codevararr1 = [100, 3, 7, 50 ];vararr2 = [5, 1, 10, 4 ];varn = arr1.length;varm = arr2.length;document.write( totalPairs(arr1, arr2, n, m));</script> | 
3
Time complexity: O(n*m), where n is the number of elements in the first input array and m is the number of elements in the second input array. This is because the code uses nested loops to iterate through both arrays and check each pair of elements. Within each iteration, the digitSum() function is called which takes constant time.
Auxiliary Space:  O(n), where n is the number of unique pairs that have the same sum of digits. This is because the code uses a set to store unique pairs of elements. The set will contain at most n elements.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







