Learn / Strings

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

MethodTimeNote
Count array (+1 for one word, -1 for the other)O(n)best for one pair
Sort both and compareO(n log n)simplest to write
Sorted letters as a map keyO(k log k) per wordgroups 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

0 of 2 solved

Check yourself

Which pair are anagrams?

Why does one count array with +1 for s and -1 for t work?

To group anagrams, what key does each word get?