Count pairs in an array having sum of elements with their respective sum of digits equal | C ++ program for the above approach ; Function to find the sum of digits of the number N ; Stores the sum of digits ; If the number N is greater than 0 ; Return the sum ; Function to find the count of pairs such that arr [ i ] + sumOfDigits ( arr [ i ] ) is equal to ( arr [ j ] + sumOfDigits ( arr [ j ] ) ; Stores the frequency of value of arr [ i ] + sumOfDigits ( arr [ i ] ) ; Traverse the given array ; Find the value ; Increment the frequency ; Stores the total count of pairs ; Traverse the map mp ; Update the count of pairs ; Return the total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( int N ) { int sum = 0 ; while ( N ) { sum += ( N % 10 ) ; N = N / 10 ; } return sum ; } int CountPair ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] + sumOfDigits ( arr [ i ] ) ; mp [ val ] ++ ; } int count = 0 ; for ( auto x : mp ) { int val = x . first ; int times = x . second ; count += ( ( times * ( times - 1 ) ) / 2 ) ; } return count ; } int main ( ) { int arr [ ] = { 105 , 96 , 20 , 2 , 87 , 96 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPair ( arr , N ) ; return 0 ; }