Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count pairs in an array such that both elements has equal set bits
Next article icon

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

Last Updated : 16 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 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)


Next Article
Count pairs in an array such that both elements has equal set bits

B

bileyroy
Improve
Article Tags :
  • Greedy
  • Mathematical
  • Hash
  • DSA
  • Arrays
  • cpp-unordered_map
  • frequency-counting
Practice Tags :
  • Arrays
  • Greedy
  • Hash
  • Mathematical

Similar Reads

  • Count array elements having sum of digits equal to K
    Given an array arr[] of size N, the task is to count the number of array elements whose sum of digits is equal to K. Examples: Input: arr[] = {23, 54, 87, 29, 92, 62}, K = 11Output: 2Explanation: 29 = 2 + 9 = 1192 = 9 + 2 = 11 Input: arr[]= {11, 04, 57, 99, 98, 32}, K = 18Output: 1 Approach: Follow
    6 min read
  • Count pairs in an array such that both elements has equal set bits
    Given an array arr [] of size N with unique elements, the task is to count the total number of pairs of elements that have equal set bits count. Examples: Input: arr[] = {2, 5, 8, 1, 3} Output: 4 Set bits counts for {2, 5, 8, 1, 3} are {1, 2, 1, 1, 2} All pairs with same set bits count are {2, 8}, {
    6 min read
  • Count pairs of indices having sum of indices same as the sum of elements at those indices
    Given an array arr[] consisting of N integers, the task is to find the number of pairs (i, j) whose sum of indices is the same as the sum elements at the indices. Examples: Input: arr[] = {0, 1, 7, 4, 3, 2}Output: 1Explanation: There exists only pair that satisfies the condition is {(0, 1)}. Input:
    9 min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Count distinct pairs from two arrays having same sum of digits
    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
    7 min read
  • Count of pairs in a given range with sum of their product and sum equal to their concatenated number
    Given two numbers A and B, the task is to find the count of pairs (X, Y) in range [A, B], such that (X * Y) + (X + Y) is equal to the number formed by concatenation of X and YExamples: Input: A = 1, B = 9 Output: 9 Explanation: The pairs (1, 9), (2, 9), (3, 9), (4, 9), (5, 9), (6, 9), (7, 9), (8, 9)
    5 min read
  • Modify a given array by replacing each element with the sum or product of their digits based on a given condition
    Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements: If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all th
    8 min read
  • Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 min read
  • Count of elements such that its sum/difference with X also exists in the Array
    Given an array arr[] and an integer X, the task is to count the elements of the array such that their exist a element [Tex]arr[i] - X [/Tex]or [Tex]arr[i] + X [/Tex]in the array.Examples: Input: arr[] = {3, 4, 2, 5}, X = 2 Output: 4 Explanation: In the above-given example, there are 4 such numbers -
    9 min read
  • Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
    Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences