Open In App

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 the same as the sum of reverse(arr[i]) and arr[j].

Examples:



Input: arr[] = {2, 15, 11, 7}
Output: 3
Explanation:
The pairs are (0, 2), (0, 3) and (2, 3). 
 

  • (0, 2): arr[0] + reverse(arr[2]) (= 2 + 11 = 13) and reverse(arr[0]) + arr[2](= 2 + 11 = 13).
  • (0, 3): arr[0] + reverse(arr[3]) (= 2 + 7 = 9) and reverse(arr[0]) + arr[3](= 2 + 7 = 9).
  • (2, 3): arr[2] + reverse(arr[3]) (= 11 + 7 = 18) and reverse(arr[2]) + arr[3](= 11 + 7 = 18).

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 steps, 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:

Below is the implementation of the above approach:




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the
// reverse of the number n
int reverse(int n)
{
    int temp = n, rev = 0, r;
 
    // Iterate until temp is 0
    while (temp) {
 
        r = temp % 10;
        rev = rev * 10 + r;
        temp /= 10;
    }
 
    // Return the reversed number
    return rev;
}
 
// Function to count number of unique
// pairs (i, j) from the array A[]
// which satisfies the given condition
void countPairs(int A[], int N)
{
    // Store the frequency of keys
    // as A[i] - reverse(A[i])
    unordered_map<int, int> u_map;
 
    // Stores count of desired pairs
    int pairs = 0;
 
    // Iterate the array A[]
    for (int i = 0; i < N; i++) {
 
        int val = A[i] - reverse(A[i]);
 
        // Add frequency of val
        // to the required answer
        pairs += u_map[val];
 
        // Increment frequency of val
        u_map[val]++;
    }
 
    // Print the number of pairs
    cout << pairs;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 15, 11, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    countPairs(arr, N);
 
    return 0;
}




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the
// reverse of the number n
static int reverse(int n)
{
    int temp = n, rev = 0, r;
 
    // Iterate until temp is 0
    while (temp > 0)
    {
        r = temp % 10;
        rev = rev * 10 + r;
        temp /= 10;
    }
 
    // Return the reversed number
    return rev;
}
 
// Function to count number of unique
// pairs (i, j) from the array A[]
// which satisfies the given condition
static void countPairs(int A[], int N)
{
     
    // Store the frequency of keys
    // as A[i] - reverse(A[i])
    HashMap<Integer, Integer> map = new HashMap<>();
 
    // Stores count of desired pairs
    int pairs = 0;
 
    // Iterate the array A[]
    for(int i = 0; i < N; i++)
    {
        int val = A[i] - reverse(A[i]);
 
        // Add frequency of val
        // to the required answer
        pairs += map.getOrDefault(val, 0);
 
        // Increment frequency of val
        map.put(val, map.getOrDefault(val, 0) + 1);
    }
 
    // Print the number of pairs
    System.out.println(pairs);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 15, 11, 7 };
    int N = arr.length;
 
    // Function Call
    countPairs(arr, N);
}
}
 
// This code is contributed by Kingash




# Python3 program for the above approach
from collections import defaultdict
 
# Function to find the
# reverse of the number n
def reverse(n):
    temp = n
    rev = 0
 
    # Iterate until temp is 0
    while (temp):
        r = temp % 10
        rev = rev * 10 + r
        temp //= 10
 
    # Return the reversed number
    return rev
 
# Function to count number of unique
# pairs (i, j) from the array A[]
# which satisfies the given condition
def countPairs(A, N):
 
    # Store the frequency of keys
    # as A[i] - reverse(A[i])
    u_map = defaultdict(int)
 
    # Stores count of desired pairs
    pairs = 0
 
    # Iterate the array A[]
    for i in range(N):
        val = A[i] - reverse(A[i])
 
        # Add frequency of val
        # to the required answer
        pairs += u_map[val]
 
        # Increment frequency of val
        u_map[val] += 1
 
    # Print the number of pairs
    print(pairs)
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [2, 15, 11, 7]
    N = len(arr)
 
    # Function Call
    countPairs(arr, N)
 
    # This code is contributed by chitranayal.




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the
// reverse of the number n
static int reverse(int n)
{
    int temp = n, rev = 0, r;
 
    // Iterate until temp is 0
    while (temp > 0)
    {
        r = temp % 10;
        rev = rev * 10 + r;
        temp /= 10;
    }
 
    // Return the reversed number
    return rev;
}
 
// Function to count number of unique
// pairs (i, j) from the array A[]
// which satisfies the given condition
static void countPairs(int []A, int N)
{
     
    // Store the frequency of keys
    // as A[i] - reverse(A[i])
    Dictionary<int,
               int> u_map = new Dictionary<int,
                                           int>();
                                            
    // Stores count of desired pairs
    int pairs = 0;
 
    // Iterate the array A[]
    for(int i = 0; i < N; i++)
    {
        int val = A[i] - reverse(A[i]);
 
        // Add frequency of val
        // to the required answer
        if (u_map.ContainsKey(val))
            pairs += u_map[val];
 
        // Increment frequency of val
        if (u_map.ContainsKey(val))
            u_map[val]++;
        else
            u_map.Add(val, 1);
    }
 
    // Print the number of pairs
    Console.Write(pairs);
}
 
// Driver Code
public static void Main()
{
    int []arr = { 2, 15, 11, 7 };
    int N = arr.Length;
 
    // Function Call
    countPairs(arr, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR




<script>
 
// Javascript program for the above approach
 
// Function to find the
// reverse of the number n
function reverse(n)
{
    var temp = n, rev = 0, r;
 
    // Iterate until temp is 0
    while (temp) {
 
        r = temp % 10;
        rev = rev * 10 + r;
        temp = parseInt(temp/10);
    }
 
    // Return the reversed number
    return rev;
}
 
// Function to count number of unique
// pairs (i, j) from the array A[]
// which satisfies the given condition
function countPairs(A, N)
{
    // Store the frequency of keys
    // as A[i] - reverse(A[i])
    var u_map = new Map();
 
    // Stores count of desired pairs
    var pairs = 0;
 
    // Iterate the array A[]
    for (var i = 0; i < N; i++) {
 
        var val = A[i] - reverse(A[i]);
 
        // Add frequency of val
        // to the required answer
        pairs += u_map.has(val)?u_map.get(val):0;
 
        // Increment frequency of val
        if(u_map.has(val))
            u_map.set(val, u_map.get(val)+1)
        else
            u_map.set(val, 1)
    }
 
    // Print the number of pairs
    document.write( pairs);
}
 
// Driver Code
var arr = [2, 15, 11, 7];
var N = arr.length;
 
// Function Call
countPairs(arr, N);
 
// This code is contributed by itsok.
</script>

Output
3

Time Complexity: O(N*log10 M), where M is the largest element in the array.
Auxiliary Space: O(N)


Article Tags :