Skip to main content

#242. Valid Anagram | LeetCode Python Solution

Problem

LeetCode Problem

  1. Valid Anagram

Python Solution

We will implement a solution to check if a string is a valid anagram using 2 for loops with HashMap.

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# Not anagram if 2 strings have different length
if len(s) != len(t):
return False

# Build character frequency dictionary for both strings
s_dict = {}
t_dict = {}

for ch in s:
if (s_dict.get(ch) is None):
s_dict[ch] = 1
else:
s_dict[ch] = s_dict[ch] + 1

for ch in t:
if (t_dict.get(ch) is None):
t_dict[ch] = 1
else:
t_dict[ch] = t_dict[ch] + 1

# Not anagram if 2 strings have different number of keys
if len(t_dict.keys()) != len(s_dict.keys()):
return False

# Not anagram if the frequency of any character does not match
for k in t_dict.keys():
if t_dict.get(k) != s_dict.get(k):
return False

return True