Exercise: Group anagrams
Two words are anagrams if they use the same letters: "eat", "tea" and
"ate". Sorting the letters gives every anagram the same key: "aet". That
key can go straight into a dict, because a string is hashable.
Exercise: finish group_anagrams(words). It returns a list of groups,
where each group is a list of words that are anagrams of each other.
- Groups come in the order their first word appears in
words. - Inside a group, words keep their order from
words. - Duplicates stay:
["a", "a"]gives[["a", "a"]]. - Compare words exactly as given. Upper and lower case letters differ.
Dicts keep insertion order, so a dict of lists already gives you the group order you need. This is a classic interview question. Sorting each word costs O(k log k), so the whole thing is O(n k log k) for n words of length k.
Press Check to run the tests.