Approach 1Optimal▶ Animated
Frequency map
Count letters in s, subtract letters in t. A leftover or a missing letter means not an anagram.
Two strings are anagrams iff they have the same multiset of characters. One map is enough: +1 for s, −1 for t.
Algorithm
- If lengths differ, return false.
- Increment counts for
s, decrement fort. - Every count must land on zero.
- Time
- O(n)
- Space
- O(σ)
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False count: dict[str, int] = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for ch in t: count[ch] = count.get(ch, 0) - 1 if count[ch] < 0: return False return True