DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Valid Anagram

Approach:
Step 1 Take both strings
Step 2 Check length if not equal return false
Step 3 Count frequency of characters in both
Step 4 Compare both counts

Why this works???
Anagram means same characters same count
if any mismatch means not anagram

Code:
def isAnagram(s,t):
if len(s)!=len(t):
return False
count={}
for ch in s:
count[ch]=count.get(ch,0)+1
for ch in t:
if ch not in count or count[ch]==0:
return False
count[ch]-=1
return True

Limitation:
Only works for lowercase letters
not for special cases

Top comments (0)