Check whether two strings are anagram of each other | Python program to check if two strings are anagrams of each other ; 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 " ; Compare count arrays ; Driver code ; Function call
NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 , str2 ) : NEW_LINE INDENT count1 = [ 0 ] * NO_OF_CHARS NEW_LINE count2 = [ 0 ] * NO_OF_CHARS NEW_LINE for i in str1 : NEW_LINE INDENT count1 [ ord ( i ) ] += 1 NEW_LINE DEDENT for i in str2 : NEW_LINE INDENT count2 [ ord ( i ) ] += 1 NEW_LINE DEDENT if len ( str1 ) != len ( str2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in xrange ( NO_OF_CHARS ) : NEW_LINE INDENT if count1 [ i ] != count2 [ i ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 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