LeetCode #242: Valid Anagram — a hash map frequency counting problem.
Two strings are anagrams if they contain the exact same characters with the exact same frequencies.
Approach: Count character frequencies in both strings. If the counts match, they're anagrams.
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Complexity: Time O(n), Space O(1) — at most 26 letters in the hash map.
def isAnagram(s, t):
if len(s) != len(t):
return False
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
for c in t:
count[c] = count.get(c, 0) - 1
if count[c] < 0:
return False
return True
isAnagram("anagram", "nagaram")
True
isAnagram("rat", "car")
False
isAnagram("listen", "silent")
True