The valid anagram leetcode problem is used to find if two strings are of equal length and of same frequency, anagram is defined as a word that is made from another word with exactly all the orginal letters only once
How do we find if a word is an anagram?
To check if a word is an anagram of another we should check if the
both words have
Condition 1: both strings must have the same number of characters
len(s) == len(t)
👉 if not → not an anagram
Condition 2: Same Characters
both strings must contain the same set of characters
s = "rat"
t = "car" → not same characters
Condition 3: Same Frequency
each character must appear the same number of times in both strings
s = "anagram"
t = "nagaram"
a → 3 times
n → 1 time
g → 1 time
r → 1 time
m → 1 time
Approach
Instead of comparing order, we compare the frequency of characters in both strings
Step 1 : check length
if lengths are not equal → return false
because anagrams must have same number of characters
Step 2 : count characters in first string
store how many times each character appears
*Step 3 : reduce count using second string
*
for each character in second string:
if character not found → return false
else decrease its count
Step 4 : final check
if all counts become zero → strings are anagrams
otherwise → not anagrams
Algorithm
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:
return False
count[ch] -= 1
for val in count.values():
if val != 0:
return False
return True
Top comments (0)