Count of pairs in Array with difference equal to the difference with digits reversed
Given an array arr[] of N integers, the task is to find the number of pairs of array elements (arr[i], arr[j]) such that the difference between the pairs is equal to the difference when the digits of both the numbers are reversed.
Examples:
Input: arr[] = {42, 11, 1, 97}
Output: 2
Explanation:
The valid pairs of array elements are (42, 97), (11, 1) as:
1. 42 – 97 = 24 – 79 = (-55)
2. 11 – 1 = 11 – 1 = (10)Input: arr[] = {1, 2, 3, 4}
Output: 6
Approach: The given problem can be solved by using Hashing which is based on the following observations:
A valid pair (i, j) will follow the equation as
=> arr[i] – arr[j] = rev(arr[i]) – rev(arr[j])
=> arr[i] – rev(arr[i]) = arr[j] – rev(arr[j])
Follow the below steps to solve the problem:
- Now, create a function reverseDigits, which will take an integer as an argument and reverse the digits of that integer.
- Store the frequency of values arr[i] – rev(arr[i]) in an unordered map, say mp.
- For each key(= difference) of frequency X the number of pairs that can be formed is given by
. - The total count of pairs is given by the sum of the value of the above expression for each frequency stored in the map mp.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the digits// of an integerint reverseDigits(int n){ // Convert the given number // to a string string s = to_string(n); // Reverse the string reverse(s.begin(), s.end()); // Return the value of the string return stoi(s);}int countValidPairs(vector<int> arr){ // Stores resultant count of pairs long long res = 0; // Stores the frequencies of // differences unordered_map<int, int> mp; for (int i = 0; i < arr.size(); i++) { mp[arr[i] - reverseDigits(arr[i])]++; } // Traverse the map and count pairs // formed for all frequency values for (auto i : mp) { long long int t = i.second; res += t * (t - 1) / 2; } // Return the resultant count return res;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4 }; cout << countValidPairs(arr); return 0;} |
6
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.



