Check whether two strings are anagram of each other | Python program to check if two strings are anagrams of each other ; function to check if two strings are anagrams of each other ; Create a count array 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 ; Driver code ; Function call
NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 , str2 ) : NEW_LINE INDENT count = [ 0 for i in range ( NO_OF_CHARS ) ] NEW_LINE i = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE count [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 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 ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE str2 = " forgeeksgeeks " NEW_LINE if ( areAnagram ( str1 , str2 ) ) : NEW_LINE INDENT print ( " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ other " ) NEW_LINE DEDENT