Practice: Valid Anagram
Same letters, different order.
Two words are anagrams if they use exactly the same letters, the same number of times. Listen and silent. Heart and earth. Pause, and think of two different ways to check.

- Same letters, same counts
- listen / silent
- Two ways to check
Sort, or count
The first way sorts both words, and compares them. Sorting is O of N log N. The second way counts the letters in each word, and compares the counts. Counting is O of N, so it's faster for long words. Run it. Both agree. Listen and silent are anagrams. Apple and pale are not.
from collections import Counter
def anagram_sort(a, b):
return sorted(a) == sorted(b)
def anagram_count(a, b):
return Counter(a) == Counter(b)
for a, b in [("listen", "silent"), ("apple", "pale")]:
print(a, b, anagram_sort(a, b), anagram_count(a, b))listen silent True True apple pale False False
Which one?
Both are correct, and both are short. Sorting is simpler to explain, and uses less memory for short words. Counting wins for long text. In an interview, give one, and mention the other with its Big O. That shows you understand the trade off.
| key | value |
|---|---|
| sorted(a) == sorted(b) | O(n log n) |
| Counter(a) == Counter(b) | O(n) |
| Short words | either is fine |
| Interview | mention both |
Summary
Anagrams have the same letter counts. Compare sorted letters, or compare Counters. Next, grouping a whole list of words into anagram families.
Key takeaways- Sort and compare
- Count and compare
- O(n log n) vs O(n)