Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 27 Aug, 2021
Geek Week

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: 2
Explanation:
Following are the pairs that satisfy the given criteria:

  1. (1, 1): The difference between 1+ sumOfDigits(1) and 1+sumOfDigits(1) is 0, thus they are equal.
  2. (2, 2): The difference between 2+sumOfDigits(2) and 2+sumOfDigits(2) is 0 , thus they are equal.

Therefore, the total number of pairs are 2.

Input: arr[] = {105, 96, 20, 2, 87, 96}
Output: 3
Following are the pairs that satisfy the given criteria:



  1. (105, 96): The difference between 105+ sumOfDigits(105) and 96+sumOfDigits(96) is 0, thus they are equal.
  2. (105, 96): The difference between 105+ sumOfDigits(105) and 96+sumOfDigits(96) is 0, thus they are equal.
  3. (96, 96): The difference between 96+ sumOfDigits(96) and 96+sumOfDigits(96) is 0, thus they are equal.

Input: arr[] = {1, 2, 3, 4}
Output: 0

Naive 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 or equal to 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++




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

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG
{
   
    // Function to find the sum of digits
    // of the number N
    static int sumOfDigits(int N)
    {
        // Stores the sum of digits
        int sum = 0;
 
        // If the number N is greater than 0
        while (N > 0) {
            sum += (N % 10);
            N = N / 10;
        }
 
        // Return the sum
        return sum;
    }
 
    // Function to find the count of pairs
    // such that arr[i] + sumOfDigits(arr[i])
    // is equal to (arr[j] + sumOfDigits(arr[j])
    static int CountPair(int arr[], int n)
    {
        // Stores the frequency of value
        // of arr[i] + sumOfDigits(arr[i])
        HashMap<Integer, Integer> mp
            = new HashMap<Integer, Integer>();
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // Find the value
            int val = arr[i] + sumOfDigits(arr[i]);
 
            // Increment the frequency
            if (mp.containsKey(val)) {
                mp.put(val, mp.get(val) + 1);
            }
            else {
                mp.put(val, 1);
            }
        }
 
        // Stores the total count of pairs
        int count = 0;
 
        // Traverse the map mp
        for (Map.Entry<Integer, Integer> x :
             mp.entrySet()) {
 
            int val = x.getKey();
            int times = x.getValue();
 
            // Update the count of pairs
            count += ((times * (times - 1)) / 2);
        }
 
        // Return the total count of pairs
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 105, 96, 20, 2, 87, 96 };
        int N = 6;
        System.out.println(CountPair(arr, N));
    }
}
 
// This code is contributed by maddler.

Python3




# Python 3 program for the above approach
 
# Function to find the sum of digits
# of the number N
def sumOfDigits(N):
    # Stores the sum of digits
    sum = 0
 
    # If the number N is greater than 0
    while (N):
        sum += (N % 10)
        N = N // 10
 
    # Return the sum
    return sum
 
# Function to find the count of pairs
# such that arr[i] + sumOfDigits(arr[i])
# is equal to (arr[j] + sumOfDigits(arr[j])
def CountPair(arr, n):
    # Stores the frequency of value
    # of arr[i] + sumOfDigits(arr[i])
    mp = {}
 
    # Traverse the given array
    for i in range(n):
        # Find the value
        val = arr[i] + sumOfDigits(arr[i])
 
        # Increment the frequency
        if val in mp:
            mp[val] += 1
        else:
            mp[val] = 1
 
    # Stores the total count of pairs
    count = 0
 
    # Traverse the map mp
    for key,value in mp.items():
        val = key
        times = value
 
        # Update the count of pairs
        count += ((times * (times - 1)) // 2)
 
    # Return the total count of pairs
    return count
 
# Driver Code
if __name__ == '__main__':
    arr = [105, 96, 20, 2, 87, 96]
    N = len(arr)
    print(CountPair(arr, N))
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
  // Function to find the sum of digits
// of the number N
static int sumOfDigits(int N)
{
   
    // Stores the sum of digits
    int sum = 0;
 
    // If the number N is greater than 0
    while (N>0) {
        sum += (N % 10);
        N = N / 10;
    }
 
    // Return the sum
    return sum;
}
 
// Function to find the count of pairs
// such that arr[i] + sumOfDigits(arr[i])
// is equal to (arr[j] + sumOfDigits(arr[j])
static int CountPair(int []arr, int n)
{
    // Stores the frequency of value
    // of arr[i] + sumOfDigits(arr[i])
    Dictionary<int, int> mp = new Dictionary<int,int>();
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Find the value
        int val = arr[i] + sumOfDigits(arr[i]);
 
        // Increment the frequency
        if(mp.ContainsKey(val))
         mp[val]++;
        else
         mp.Add(val,1);
    }
 
    // Stores the total count of pairs
    int count = 0;
 
    // Traverse the map mp
    foreach(KeyValuePair<int, int> entry in mp) {
 
        int val = entry.Key;
        int times = entry.Value;
 
        // Update the count of pairs
        count += ((times * (times - 1)) / 2);
    }
 
    // Return the total count of pairs
    return count;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 105, 96, 20, 2, 87, 96 };
    int N = arr.Length;
    Console.Write(CountPair(arr, N));
}
}
 
// This code is contributed by ipg2016107.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
        // Function to find the sum of digits
        // of the number N
        function sumOfDigits(N) {
            // Stores the sum of digits
            let sum = 0;
 
            // If the number N is greater than 0
            while (N != 0) {
                sum = sum + (N % 10);
                N = Math.floor(N / 10);
            }
 
            // Return the sum
            return sum;
        }
 
        // Function to find the count of pairs
        // such that arr[i] + sumOfDigits(arr[i])
        // is equal to (arr[j] + sumOfDigits(arr[j])
        function CountPair(arr, n) {
            // Stores the frequency of value
            // of arr[i] + sumOfDigits(arr[i])
            let mp = new Map();
 
            // Traverse the given array
            for (let i = 0; i < n; i++) {
 
                // Find the value
 
 
                let val = arr[i] + sumOfDigits(arr[i]);
                // Increment the frequency
                if (mp.has(val)) {
                    mp.set(val, mp.get(val) + 1);
                }
                else {
                    mp.set(val, 1);
                }
            }
 
            // Stores the total count of pairs
            let count = 0;
 
            // Traverse the map mp
            for (let [key, value] of mp) {
 
                // Update the count of pairs
 
 
                count = count + (value * (value - 1)) / 2;
            }
 
            // Return the total count of pairs
            return count;
        }
 
        // Driver Code
 
        let arr = [105, 96, 20, 2, 87, 96];
        let N = arr.length;
        document.write(CountPair(arr, N))
 
 
// This code is contributed by Potta Lokesh
    </script>
Output
3

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :