Count 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
function reverse ( num ) { let rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = Math . floor ( num / 10 ) ; } return rev_num ; } function countReverse ( arr , n ) { let freq = new 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 ; 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 ) ; } if ( freq . has ( reverse ( arr [ i ] ) ) ) { res += freq . get ( reverse ( arr [ i ] ) ) ; } } return res ; } let a = [ 16 , 61 , 12 , 21 , 25 ] ; let n = a . length ; document . write ( countReverse ( a , n ) ) ;