Signal
"Anagram" or "same letters rearranged" means compare character frequencies —
count letters in each string and check the counts match.
Approach
If the lengths differ, they can't be anagrams — bail immediately. Otherwise,
count character frequencies for each string and compare the two counts.
Skeleton
if len(s) != len(t): return False
counts = defaultdict(int)
for ch in s: counts[ch] += 1
for ch in t: counts[ch] -= 1
return all(v == 0 for v in counts.values())
Solution
from collections import Counter
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return Counter(s) == Counter(t)
Complexity
O(n) time to build and compare the two counters. O(1) space for a fixed
alphabet (e.g. 26 lowercase letters), O(k) for k distinct characters otherwise.
Pitfalls
sorted(s) == sorted(t) is correct but O(n log n) — name it as a fallback,
lead with linear counting.
- Decide up front whether case and non-ASCII letters count — the standard
version is case-sensitive, lowercase letters only.
- Skipping the length check is a common bug: without it, mismatched extra
characters in the longer string can still leave the shared keys' counts at
zero while the check quietly passes.