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