# Count pairs in an array having sum of elements with their respective sum of digits equal

Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits.Examples:Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that satisfy the given criteria:(1, 1): The difference between 1 and 1 is 0 and the difference between their sum of digits is (1 – 1) = 0, which is equal.(1, 1): The difference between 2 and 2 is 0 and the difference between their sum of digits is (2 – 2) = 0, which is equal.Therefore, the total number of pairs are 2.Input: arr[] = {1, 2, 3, 4}Output: 0Naive Approach: The simplest approach to solve the problem is to generate all possible pairs of the given array and count those pairs that satisfy the given criteria. After checking for all the pairs print the total count of pairs obtained.Time Complexity: O(N2)Auxiliary Space: O(1)Efficient Approach: The above approach can also be optimized by storing the sum of elements with its sum of digits in a HashMap and then count the total number of pairs formed accordingly. Follow the steps given below to solve the problem:Initialize an unordered_map, M that stores the frequency of the sum of elements with its sum of digits for each array element.Traverse the given array and and increment the frequency of (arr[i] + sumOfDigits(arr[i])) in the map M.Initialize a variable, say count as 0 that stores the total count of resultant pairs.Traverse the given map M and if the frequency of any element, say F is greater than 2, then increment the value of count by (F*(F – 1))/2.After completing the above steps, print the value of count as the resultant count of pairs.Below is the implementation of the above approach:C++  #include 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 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);    cout 