Wednesday, 27 Oct 2021

# Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]

Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is same as the sum of reverse(arr[i]) and arr[j].
Examples:

Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3).
(0, 2): arr + reverse(arr) (= 2 + 11 = 211) and reverse(arr) + arr(= 2 + 11 = 211).
(0, 3): arr + reverse(arr) (= 2 + 7 = 27) and reverse(arr) + arr(= 2 + 7 = 27).
(2, 3): arr + reverse(arr) (= 11 + 7 = 117) and reverse(arr) + arr(= 11 + 7 = 117).
Input: A[] = {22, 115, 7, 313, 17, 23, 22}Output: 6

Naive Approach: The simplest approach is to generate all possible pairs of the given array and if any pair of elements satisfy the given conditions then count these pairs. After completing the above stepsm, print the value of count as the result.Time Complexity: O(N2*log M), where M is the maximum element in A[]Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using Hashing technique and rewriting the equation as:

A[i] + reverse(A[j]) = reverse(A[i]) + A[j]=> A[i] – reverse(A[i]) = A[j] – reverse(A[j])
Now, the idea is to count the frequency of (A[i] – reverse(A[i])) for every element arr[i] and then count possible number of valid pairs satisfying the given condition. Follow the steps below to solve the problem:
Maintain a Hashmap, say u_map to store the frequency count of A[i] – reverse(A[i]) for any index i.
Initialize a variable pairs to store the number of pairs that satisfy the given condition.
Traverse the given array A[] using the variable i and perform the following operations:
Store the frequency of A[i] – reverse(A[i]) in val.
Increment pairs by val.
Update the frequency of val in u_map.

After completing the above steps, print the value of pairs as the result.
Below is the implementation of the above approach:

C++

#include
using namespace std;

int reverse(int n)
{
int temp = n, rev = 0, r;

while (temp) {

r = temp % 10;
rev = rev * 10 + r;
temp /= 10;
}

return rev;
}

void countPairs(int A[], int N)
{

unordered_map u_map;

int pairs = 0;

for (int i = 0; i < N; i++) {            int val = A[i] - reverse(A[i]);                              pairs += u_map[val];                     u_map[val]++;     }             cout