💡
Exercise 24

Valid Anagram 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

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.

📋 Instructions
Implement `isAnagram(s, t)` that returns True if t is an anagram of s. Use a dictionary to count character frequencies. Don't use `sorted()` — practice the hash map approach!
First check len(s) != len(t) → return False. Create 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.
⚠️ Try solving it yourself first — you'll learn more!
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
🧪 Test Cases
Input
isAnagram("anagram", "nagaram")
Expected
True
Boolean check
Input
isAnagram("rat", "car")
Expected
False
Boolean check
Input
isAnagram("listen", "silent")
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.