Number of index pairs such that s [ i ] and s [ j ] are anagrams | Function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; To store the count of sorted strings ; Traverse all strings and store in the map ; Sort the string ; If string exists in map , increment count Else create key value pair with count = 1 ; To store the number of pairs ; Traverse through the map ; Count the pairs for each string ; Return the required answer ; Driver code ; Function call
def anagram_pairs ( s , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp_str = " " . join ( sorted ( s [ i ] ) ) NEW_LINE if temp_str in mp : NEW_LINE INDENT mp [ temp_str ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ temp_str ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for k in mp . values ( ) : NEW_LINE INDENT ans += ( k * ( k - 1 ) ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = [ " aaab " , " aaba " , " baaa " , " cde " , " dec " ] NEW_LINE n = len ( s ) NEW_LINE print ( anagram_pairs ( s , n ) ) NEW_LINE DEDENT