Anagrams
Two words are anagrams when they use exactly the same letters the same number of times. Compare their letter counts, or their sorted letters. A sorted copy (or a count signature) also works as a key, so a hash map groups many words by anagram class in one pass.
How to recognise it
- The question says "anagram", "rearrange the letters", or "same characters in any order".
- Words must be grouped, counted or matched by their letters, ignoring order.
The idea in one picture
Tip the letters of a word into a bag. Two words are anagrams when their bags hold the same tiles. Counting tiles or sorting them into a line are two ways of comparing bags.
Two ways to compare bags
| Method | Time | Note |
|---|---|---|
| Count array (+1 for one word, -1 for the other) | O(n) | best for one pair |
| Sort both and compare | O(n log n) | simplest to write |
| Sorted letters as a map key | O(k log k) per word | groups many words |
Template: group by key
groups = empty map from key to list (keeping first-seen order)
for each word w:
key = sorted letters of w
add w to groups[key]
return the lists in groups
Common mistakes
- Forgetting to check that the lengths match.
- Using a set of letters, which ignores how many times each appears.
- Using a plain hash map in a language where its order is not fixed, when the answer's order matters.
Problems
- Valid Anagrameasyguide ready
- Given a sequence of words, print all anagrams togethermediumguide ready