← Problem setPython
#242EasyArrays & hashing
Valid Anagram
The tell: Two strings, same characters, order irrelevant.
How you get there
- 1An anagram is defined entirely by its character counts.
- 2Counter builds both in one pass each and compares in O(alphabet).
- 3Sorting also works at O(n log n) — mention it, then give the linear answer.
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)- Time
- O(n)
- Space
- O(1) over a fixed alphabet
What goes wrong
Skipping the length check is harmless here but matters when you hand-roll the counting loop.