How to check if two strings are anagrams in Python
Strings are a vastly used data type in Python to store all kinds of text data: characters, alphabets, numbers, and alphanumeric. They are immutable; however, we can use different methods to manipulate them to achieve the desired results.
What are anagram strings?
Two strings are said to be anagrams if they have the same frequency of each character, which means we can obtain the other string upon rearranging one string.
For example, STUDY and DUSTY are anagrams because they have the same length, and each character in STUDY has a corresponding equal character in DUSTY. On the other hand STING and NIGHT are not anagrams despite having the same length because S and H have no corresponding equal characters.
Using sorted() function
In this method, we use the sorted() function to arrange the characters in each string in ascending order and check if they are the same.
def checkAnagram(string1 , string2):print('String 1 : ' + string1)print('String 2 : ' + string2)#convert the strings to lowercasestring1 = string1.lower()string2 = string2.lower()#check if length is sameif(len(string1) != len(string2)):print('\nNot Anagram\n')else:#sort the stringssortString1 = sorted(string1)sortString2 = sorted(string2)#check if sameif(sortString1 == sortString2):print('\nAre Anagram\n')else:print('\nNot Anagram\n')string1 = "Study"string2 = "Dusty"checkAnagram(string1 , string2)string3 = "Sting"string4 = "Night"checkAnagram(string3 , string4)
Code explanation
Line 1: Define the
checkAnagram()function that takes two strings as parameters and prints if they are anagrams or not.Lines 3–4: Print both the strings on the console.
Lines 7–8: Use the built-in
lower()function to convert all characters to lowercase because Python is a case-sensitive language.Line 11: Use the
len()built-in function to get the length of each string and compare using the!=operator. If different lengths, print 'Not Anagram'.Lines 16–17: Use the
sorted()built-in function to arrange the characters of each string in ascending order.Line 20: Compare both sorted strings and check if they are the same using the
==operator. If same, print 'Are Anagram'; else, print 'Not Anagram'.Line 28: Call the
checkAnagram()function forstring1andstring2and the output, in this case, will be 'Are Anagram'.Line 32: Call the
checkAnagram()function forstring3andstring4and the output, in this case, will be 'Not Anagram'.
Using a list and dictionary
In this method, we convert the strings in a list and save each character and its frequency in a dictionary object. The values in the dictionary against each unique key are used to check if strings are anagrams.
def checkAnagram(string1 , string2):print('String 1 : ' + string1)print('String 2 : ' + string2)#convert the strings to lowercasestring1 = string1.lower()string2 = string2.lower()#convert strings to listslist1 = list(string1)list2 = list(string2)#create a dictionarycount = {}#save char frequency as values against each charfor char in list1:if char not in count:count[char] = 0count[char] += 1for char in list2:if char not in count:print('\nNot Anagram\n')breakcount[char] -= 1else:#Check if dictionary emptyfor c in count.values():if c != 0:print('\nNot Anagram\n')breakelse:print('\nAre Anagram\n')string1 = "Study"string2 = "Dusty"checkAnagram(string1 , string2)string3 = "Sting"string4 = "Night"checkAnagram(string3 , string4)
Code explanation
Line 1: Define the
checkAnagram()function that takes two strings as parameters and prints if they are anagrams.Lines 3–4: Print both the strings on the console.
Lines 7–8: Use built-in
lower()function to convert all characters to lowercase because Python is a case-sensitive language.Lines 11–12: Convert both the strings to a list and assign them to
list1andlist2variables, respectively.Line 15: Create a
countdictionary to store each character as a key and its frequency as a value.Lines 18–21: Loop through
list1, create a key for each unique character in the string and increment the value by 1 if the same character appears again.Lines 23–27: Loop through
list2, check for the key against each character in the string and decrement the value by 1 if the key is found; else, print 'Not Anagram'.Lines 31–36: Loop through the values in the
countdictionary, and check if the value against any key is not zero. If found not equal to zero, print 'Not Anagram'; else, print 'Are Anagram'.Line 41: Call the
checkAnagram()function forstring1andstring2and the output, in this case, will be 'Are Anagram'.Line 45: Call the
checkAnagram()function forstring3andstring4and the output, in this case, will be 'Not Anagram'.
Comparing methods
Method | Time Complexity | Space Complexity |
Using sorted() function | O(nlogn) | O(1) |
Using list and dictionary | O(n) | O(n) |
Test your understanding
What other method can be used to verify if strings are anagrams using characters’ frequency?
Free Resources