How to check if two strings are anagrams of each other in nLog(n)

What is an anagram?

An anagram is a word made by rearranging an original word’s letters to make a new word.

For example, “listen” and “silent” are anagrams of each other because we can create them by rearranging the letters. In other words, the strings contain the same letters, but in a different order.

1 of 3

How to check if two strings are anagrams of each other

Any two strings are anagrams of each other if the letters in both of the strings are the same.

step 1 : sort both strings
step 1 : compare the strings

To sort the strings, we will use the sorted() function, which returns a sorted string. Then, we compare the sorted strings using the == operator, which returns True if the strings are anagrams of each other.

Below is the Python code used to check if two strings are anagrams of each other:

def anagram(str1, str2):
if(sorted(str1)== sorted(str2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
s1 ="elbow"
s2 ="below"
anagram(s1, s2)

Free Resources