Here’s Google’s definition of an Anagram: a word, phrase, or name formed by rearranging the letters of another, such as spar, formed from rasp.
Let’s see how we can write a program in Python to check whether the given input strings s1 and s2 are anagrams of each other.
def anagram1(s1, s2):
# remove spaces and lowercase every letter
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
return sorted(s1) == sorted(s2)
anagram1('clint eastwood', 'old west action') # True
That’s done using in-built python functions called replace, lower and sorted where we replace all the spaces with nothing and transform the strings to lowercase before comparing them to each other using the “sorted” function.
That works just fine but let’s see how we can do this manually without using the “sorted” in-built function.
def anagram2(s1, s2):
# remove spaces and lowercase every letter
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
# Edge case check
if len(s1) != len(s2):
return False
# maintain a dict of letters
# and count occurrence of each letter
count = {}
for letter in s1:
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for letter in s2:
if letter in count:
count[letter] -= 1
else:
count[letter] = 1
for letter in count:
if count[letter] != 0:
return False
return True
anagram2('clint eastwood', 'old west action') # True
Here we replace spaces and transform the strings to lower case (same as before). Next we run an edge case check to see if length of those strings are not equal. If they aren’t, we stop!
If they are equal, we use dictionary to track the count of each letter. When we check the first string, we increment the count. When we check the second string, we decrement it.
Finally we check if count isn’t zero. If it isn’t, we stop. Else we return True. And that is how we check for Anagrams manually 🙂