Print all pairs of anagrams in a given array of strings | Python3 program to find best meeting point in 2D array ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; This function prints all anagram pairs in a given array of strings ; Driver Code
NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 : str , str2 : str ) -> bool : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) and i < len ( str2 ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) ] += 1 NEW_LINE count [ ord ( str2 [ i ] ) ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT if len ( str1 ) != len ( str2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if count [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT def findAllAnagrams ( arr : list , n : int ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if areAnagram ( arr [ i ] , arr [ j ] ) : NEW_LINE INDENT print ( arr [ i ] , " is ▁ anagram ▁ of " , arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksquiz " , " geeksforgeeks " , " abcd " , " forgeeksgeeks " , " zuiqkeegs " ] NEW_LINE n = len ( arr ) NEW_LINE findAllAnagrams ( arr , n ) NEW_LINE DEDENT