Strings: Anagrams

Two strings are anagrams when they use the same letters the same number of times: "listen" and "silent". Counting is the pattern here, and collections.Counter does the counting in O(n).

Counter("hello")  # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

Two Counters compare equal when they hold the same counts. sorted(a) == sorted(b) also works and is O(n log n). Both are fine in an interview if you say the cost.

The signal: "same letters", "rearrange", "permutation of", or grouping words by their letters. To group, use a key that is the same for all anagrams, like "".join(sorted(word)).

A common mistake: removing letters one by one from a list with list.remove. Each remove is O(n), so the whole check is O(n²).

Ask in an interview whether case and spaces count. Here they do.

Exercise: finish is_anagram so it returns True when a and b are anagrams. Press Check to run the tests.