Open In App

Count pairs in array such that one element is reverse of another

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[], the task is to count the pairs in the array such that the elements are the reverse of each other.

Examples: 

Input: arr[] = { 16, 61, 12, 21, 25 } 
Output:
Explanation: 
The 2 pairs such that one number is the reverse of the other are {16, 61} and {12, 21}.

Input: arr[] = {10, 11, 12} 
Output: 0  

Method 1:

Approach: The idea is to use nested loops to get all the possible pairs of numbers in the array. Then, for each pair, check whether an element is a reverse of another. If it is, then increase the required count by one. When all the pairs have been checked, they return or print the count of such pairs. 

Below is the implementation of the above approach: 

C++




// C++ program to count the pairs in array
// such that one element is reverse of another
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse the digits
// of the number
int reverse(int num)
{
    int rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
int countReverse(int arr[], int n)
{
    int res = 0;
 
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
 
            // Increment count if one is
            // the reverse of other
            if (reverse(arr[i]) == arr[j]) {
                res++;
            }
 
    return res;
}
 
// Driver code
int main()
{
    int a[] = { 16, 61, 12, 21, 25 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countReverse(a, n);
    return 0;
}


Java




// Java program to count the pairs in array
// such that one element is reverse of another
 
class Geeks {
    // Function to reverse the digits
    // of the number
    static int reverse(int num) {
        int rev_num = 0;
 
        // Loop to iterate till the number is
        // greater than 0
        while (num > 0) {
 
            // Extract the last digit and keep
            // multiplying it by 10 to get the
            // reverse of the number
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
 
    // Function to find the pairs from the
    // such that one number is reverse of
    // the other
    static int countReverse(int arr[], int n) {
        int res = 0;
 
        // Iterate through all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
 
                // Increment count if one is
                // the reverse of other
                if (reverse(arr[i]) == arr[j]) {
                    res++;
                }
 
        return res;
    }
 
    // Driver code
    public static void main(String[] args) {
        int a[] = { 16, 61, 12, 21, 25 };
        int n = a.length;
        System.out.print(countReverse(a, n));
    }
}
 
// This code is contributed by Rajnis09


Python3




# Python3 program to count the pairs in array
# such that one element is reverse of another
 
# Function to reverse the digits
# of the number
def reverse(num):
    rev_num = 0
 
    # Loop to iterate till the number is
    # greater than 0
    while (num > 0):
 
        # Extract the last digit and keep
        # multiplying it by 10 to get the
        # reverse of the number
        rev_num = rev_num * 10 + num % 10
        num = num // 10
 
    return rev_num
 
# Function to find the pairs from the
# such that one number is reverse of
# the other
def countReverse(arr,n):
    res = 0
 
    # Iterate through all pairs
    for i in range(n):
        for j in range(i + 1, n):
 
            # Increment count if one is
            # the reverse of other
            if (reverse(arr[i]) == arr[j]):
                res += 1
 
    return res
 
# Driver code
if __name__ == '__main__':
    a =  [16, 61, 12, 21, 25]
    n =  len(a)
    print(countReverse(a, n))
 
# This code is contributed by Surendra_Gangwar


C#




// C# program to count the pairs in array
// such that one element is reverse of another
using System;
  
class GFG
{
  
// Function to reverse the digits
// of the number
static int reverse(int num)
{
    int rev_num = 0;
  
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
  
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
  
// Function to find the pairs from the
// such that one number is reverse of
// the other
static int countReverse(int []arr, int n)
{
    int res = 0;
  
    // Iterate through all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
  
            // Increment count if one is
            // the reverse of other
            if (reverse(arr[i]) == arr[j]) {
                res++;
            }
  
    return res;
}
  
// Driver code
public static void Main(String []arr)
{
    int []a = { 16, 61, 12, 21, 25 };
    int n = a.Length;
    Console.Write(countReverse(a, n));
}
}
 
// This code is contributed by shivanisinghss2110


Javascript




<script>
 
// Javascript program to count the pairs in array
// such that one element is reverse of another
 
// Function to reverse the digits
// of the number
function reverse(num)
{
    var rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = parseInt(num / 10);
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
function countReverse(arr, n)
{
    var res = 0;
 
    // Iterate through all pairs
    for (var i = 0; i < n; i++)
        for (var j = i + 1; j < n; j++)
 
            // Increment count if one is
            // the reverse of other
            if (reverse(arr[i]) == arr[j]) {
                res++;
            }
 
    return res;
}
 
// Driver code
var a = [ 16, 61, 12, 21, 25 ];
var n = a.length;
document.write( countReverse(a, n));
 
// This code is contributed by noob2000.
</script>


Output: 

2

 

Time Complexity: O(N2 * log10M), where N is the size of the given array and M is the maximum element in the array.
Auxiliary Space: O(1)

Method 2: (Using Hash-Map)

We can observe that the most expensive operation here is searching for the reversed element in the array(which takes O(N)). By using a hash map, this can be reduced to O(1). 

Approach: The idea is to store all the elements of the array in the hash map(by increasing the frequency of the present element to tackle the problem of duplicates) and check how many times the reversed element is repeated and increase the count by that frequency. To avoid recounting the number when it is a palindrome or when we visit its reverse, we need to delete the present number from the hash map(this is achieved by decreasing the frequency of that number).

C++




// C++ program to count the pairs in array
// such that one element is reverse of another
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse the digits
// of the number
int reverse(int num)
{
    int rev_num = 0;
 
    // Loop to iterate till the number is
    // greater than 0
    while (num > 0) {
 
        // Extract the last digit and keep
        // multiplying it by 10 to get the
        // reverse of the number
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
 
// Function to find the pairs from the array
// such that one number is reverse of
// the other
int countReverse(int arr[], int n)
{
    unordered_map<int, int> freq;
 
    // Iterate over every element in the array
    // and increase the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
        ++freq[arr[i]];
 
    int res = 0;
    // Iterate over every element in the array
    for (int i = 0; i < n; i++){
 
        // remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        --freq[arr[i]];
 
        // Increment the count
        // by the frequency of
        // reverse of the number
        res += freq[reverse(arr[i])];
    }
    return res;
}
 
// Driver code
int main() {
    int a[] = { 16, 61, 12, 21, 25 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countReverse(a, n) << '\n';
    return 0;
}


Java




// Java program to count the
// pairs in array such that
// one element is reverse of
// another
import java.util.*;
class GFG{
     
// Function to reverse the digits
// of the number
public static int reverse(int num)
{
  int rev_num = 0;
 
  // Loop to iterate till
  // the number is greater
  // than 0
  while (num > 0)
  {
    // Extract the last digit
    // and keep multiplying it
    // by 10 to get the reverse
    // of the number
    rev_num = rev_num * 10 +
              num % 10;
    num = num / 10;
  }
  return rev_num;
}
      
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
public static int countReverse(int arr[],
                               int n)
{
  HashMap<Integer,
          Integer> freq =
          new HashMap<>();
 
  // Iterate over every element
  // in the array and increase
  // the frequency of the element
  // in hash map
  for(int i = 0; i < n; ++i)
  {
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) + 1);
    }
    else
    {
      freq.put(arr[i], 1);
    }
  }
 
  int res = 0;
   
  // Iterate over every element
  // in the array
  for (int i = 0; i < n; i++)
  {
    // remove the current element from
    // the hash map by decreasing the
    // frequency to avoid counting
    // when the number is a palindrome
    // or when we visit its reverse
    if(freq.containsKey(arr[i]))
    {
      freq.replace(arr[i],
      freq.get(arr[i]) - 1);
    }
    else
    {
      freq.put(arr[i], -1);
    }
 
    // Increment the count
    // by the frequency of
    // reverse of the number
    if(freq.containsKey(reverse(arr[i])))
    {
      res += freq.get(reverse(arr[i]));
    }
  }
  return res;
}
 
// Driver code   
public static void main(String[] args)
{
  int a[] = {16, 61, 12, 21, 25};
  int n = a.length;
  System.out.println(countReverse(a, n));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3




# Python3 program to count
# the pairs in array such
# that one element is reverse
# of another
from collections import defaultdict
 
# Function to reverse
# the digits of the number
def reverse(num):
 
    rev_num = 0
 
    # Loop to iterate till
    # the number is greater than 0
    while (num > 0):
 
        # Extract the last digit and keep
        # multiplying it by 10 to get the
        # reverse of the number
        rev_num = rev_num * 10 + num % 10
        num = num // 10
  
    return rev_num
 
# Function to find the pairs
# from the array such that
# one number is reverse of
# the other
def countReverse(arr, n):
 
    freq = defaultdict (int)
 
    # Iterate over every element
    # in the array and increase
    # the frequency of the element
    # in hash map
    for i in range (n):
        freq[arr[i]] += 1
 
    res = 0
     
    # Iterate over every
    # element in the array
    for i in range (n):
 
        # remove the current element from
        # the hash map by decreasing the
        # frequency to avoid counting
        # when the number is a palindrome
        # or when we visit its reverse
        freq[arr[i]] -= 1
 
        # Increment the count
        # by the frequency of
        # reverse of the number
        res += freq[reverse(arr[i])]
    
    return res
 
# Driver code
if __name__ == "__main__":
   
    a = [16, 61, 12, 21, 25]
    n = len(a)
    print (countReverse(a, n))
     
# This code is contributed by Chitranayal


C#




// C# program to count the
// pairs in array such that
// one element is reverse of
// another
using System;
using System.Collections.Generic;  
 
class GFG{
     
// Function to reverse the digits
// of the number
static int reverse(int num)
{
    int rev_num = 0;
     
    // Loop to iterate till
    // the number is greater
    // than 0
    while (num > 0)
    {
         
        // Extract the last digit
        // and keep multiplying it
        // by 10 to get the reverse
        // of the number
        rev_num = rev_num * 10 +
                      num % 10;
        num = num / 10;
    }
    return rev_num;
}
       
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
static int countReverse(int[] arr, int n)
{
    Dictionary<int,
               int> freq = new Dictionary<int,
                                          int>(); 
     
    // Iterate over every element
    // in the array and increase
    // the frequency of the element
    // in hash map
    for(int i = 0; i < n; ++i)
    {
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]++;
        }
        else
        {
            freq.Add(arr[i], 1);
        }
    }
     
    int res = 0;
     
    // Iterate over every element
    // in the array
    for(int i = 0; i < n; i++)
    {
         
        // Remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        if (freq.ContainsKey(arr[i]))
        {
            freq[arr[i]]--;
        }
        else
        {
            freq.Add(arr[i], -1);
        }
     
        // Increment the count
        // by the frequency of
        // reverse of the number
        if (freq.ContainsKey(reverse(arr[i])))
        {
            res += freq[reverse(arr[i])];
        }
    }
    return res;
}
 
// Driver code   
static void Main()
{
    int[] a = { 16, 61, 12, 21, 25 };
    int n = a.Length;
     
    Console.WriteLine(countReverse(a, n));
}
}
 
// This code is contributed by divyesh072019


Javascript




<script>
// Javascript program to count the
// pairs in array such that
// one element is reverse of
// another
 
// Function to reverse the digits
// of the number
function reverse(num)
{
    let rev_num = 0;
  
      // Loop to iterate till
      // the number is greater
      // than 0
      while (num > 0)
      {
        // Extract the last digit
        // and keep multiplying it
        // by 10 to get the reverse
        // of the number
        rev_num = rev_num * 10 +
              num % 10;
        num = Math.floor(num / 10);
      }
      return rev_num;
}
 
// Function to find the pairs
// from the array such that
// one number is reverse of the
// other
function countReverse(arr,n)
{
     let freq = new Map();
  
      // Iterate over every element
      // in the array and increase
      // the frequency of the element
      // in hash map
      for(let i = 0; i < n; ++i)
      {
        if(freq.has(arr[i]))
        {
          freq.set(arr[i],
          freq.get(arr[i]) + 1);
        }
        else
        {
          freq.set(arr[i], 1);
        }
      }
  
     let res = 0;
    
     // Iterate over every element
      // in the array
      for (let i = 0; i < n; i++)
      {
        // remove the current element from
        // the hash map by decreasing the
        // frequency to avoid counting
        // when the number is a palindrome
        // or when we visit its reverse
        if(freq.has(arr[i]))
        {
              freq.set(arr[i],
              freq.get(arr[i]) - 1);
        }
        else
        {
              freq.set(arr[i], -1);
        }
  
        // Increment the count
        // by the frequency of
        // reverse of the number
        if(freq.has(reverse(arr[i])))
        {
              res += freq.get(reverse(arr[i]));
        }
      }
      return res;
}
 
// Driver code  
let a=[16, 61, 12, 21, 25];
let n = a.length;
document.write(countReverse(a, n));
 
 
// This code is contributed by avanitrachhadiya2155
</script>


Output

2

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



Similar Reads

Count pairs in array such that one element is power of another
Given an array arr[], the task is to count the pairs in the array such that one element is the power of another in each pair.Examples: Input: arr[] = {16, 2, 3, 9} Output: 2 The 2 pairs are (16, 2) and (3, 9) Input: arr[] = {2, 3, 5, 7} Output: 0 Approach: After taking the array as input, first we need to find out all the possible pairs in that arr
5 min read
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: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Count pairs in an array such that at least one element is prime
Given an array arr[] of distinct elements, the task is to count the total number of distinct pairs in which at least one element is prime. Examples: Input: arr[] = {1, 3, 10, 7, 8} Output: 7 Pairs with at least one prime are (1, 3), (1, 7), (3, 1), (3, 7), (3, 8), (10, 7), (7, 8). Input:arr[]={4, 6, 8, 2, 9}; Output: 4 Approach: First precompute al
12 min read
Maximum count of pairs such that element at each index i is included in i pairs
Given an array arr[] and an integer N, the task is to find the maximum number of pairs that can be formed such that ith index is included in almost arr[i] pairs. Examples: Input: arr[] = {2, 2, 3, 4} Output: 51 32 42 43 43 4Explanation: For the given array, a maximum of 5 pairs can be created where 1st index is included in 1 pair, 2nd index in 2 pa
6 min read
Count elements that are divisible by at-least one element in another array
Given two arrays arr1[] and arr2[]. The task is to find the count of such elements in the first array whose at-least one factor is present in the second array.Examples: Input : arr1[] = {10, 2, 13, 4, 15} ; arr2[] = {2, 4, 5, 6} Output : 4 There is no factor of 13 which is present in the second array. Except 13, factors of the rest 4 elements of th
8 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Count pairs in an array such that frequency of one is at least value of other
Given an array A[] of integers. The task is to find the total number of ordered pairs of positive integers (X, Y) such that X occurs in A[] at least Y times and Y occurs in A at least X times. Examples: Input : A[] = { 1, 1, 2, 2, 3 } Output : 4 Ordered pairs are -&gt; { [1, 1], [1, 2], [2, 1], [2, 2] } Input : A = { 3, 3, 2, 2, 2 } Output : 3 Orde
5 min read
Maximum count of common divisors of A and B such that all are co-primes to one another
Given two integers A and B. The task is to find the count of maximum elements from the common divisors of A and B such that all selected elements are co-prime to one another.Examples: Input: A = 12, B = 18 Output: 3 Common divisors of A and B are 1, 2, 3 and 6. Select 1, 2, and 3. All the pairs are co primes to one another i.e. gcd(1, 2) = gcd(1, 3
5 min read
Count of arrays in which all adjacent elements are such that one of them divide the another
Given two positive integer n and n. The task is to find the number of arrays of size n that can be formed such that : Each element is in range [1, m]All adjacent element are such that one of them divide the another i.e element Ai divides Ai + 1 or Ai + 1 divides Ai + 2. Examples: Input : n = 3, m = 3. Output : 17 {1,1,1}, {1,1,2}, {1,1,3}, {1,2,1},
9 min read
Count of pairs from arrays A and B such that element in A is greater than element in B at that index
Given two arrays A[] and B[] of size N, the task is to count the maximum number of pairs, where each pair contains one from each array, such that A[i] &gt; B[i]. Also the array A can be rearranged any number of times. Examples: Input: A[] = {20, 30, 50}, B[]= {60, 40, 25} Output: 2 Explanation: Initially: A[0] = 20 &lt; B[0] = 60 A[1] = 30 &lt; B[1
7 min read
Article Tags :
Practice Tags :