Count pairs in array such that one element is reverse of another | Python3 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
from collections import defaultdict NEW_LINE def reverse ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num // 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def countReverse ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] -= 1 NEW_LINE res += freq [ reverse ( arr [ i ] ) ] NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 61 , 12 , 21 , 25 ] NEW_LINE n = len ( a ) NEW_LINE print ( countReverse ( a , n ) ) NEW_LINE DEDENT