Leet Code
brian | Published: Jan. 19, 2025, 11:50 a.m. | Updated: July 10, 2025, 12:07 a.m.
'''
Given two strings s and t, return true if t is an
anagram
of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
'''
class Solution(object):
def isAnagram(self, word1:str, word2:str):
#check if they are not both the same lenght then obviously they cant be
#anagrams, so why bother checking the bottom... return False
if len(word1)!= len(word2):
return False
#create empty dictionary
anagram = {}
#here im creating the dictionary with the letters as keys and the values as the
#number of times the letter has been encountered.
#i will need this info when i loop throgh the second word to compare them both
for char in word1:
#if the key exists return
#if it doesnt, set the value to 0
anagram.setdefault(char, 0)
#add one because we encounter the letter
anagram[char]+=1
for char in word2:
if char in anagram:
#if the character is in the anagram then - 1 the value
anagram[char]-= 1
#if value goes below 0 that means there were more of the letter in word2
#than in word1, so return False because its no anagram
if anagram[char] < 0:
return False
else:
#if the current character is not in word 1 then its not an anagram
#return False
return False
#if we get up to this point then that measn it is an anagram
return True
if __name__ == '__main__':
s = 'arc'
c = 'car'
obj1 = Solution()
print(obj1.isAnagram(s, c))