Python coding

Group words by their letters

Given a list of lowercase words words, group together the words that are anagrams of each other: they use exactly the same letters, the same number of times, in any order. Return the groups as a list of lists. Every word goes in exactly one group, and a word that appears twice in the input appears twice in its group. The order of the groups, and of the words inside each group, does not matter.

Words may be empty strings. Aim for one pass over words.

Besides the tests, one large input (1,500 words) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • group_by_letters(["stop","pots","tops","opt","top","dog"]) → [["stop","pots","tops"],["opt","top"],["dog"]]
  • group_by_letters(["aab","abb","aba","bab"]) → [["aab","aba"],["abb","bab"]]
  • group_by_letters(["ab","ba","ab"]) → [["ab","ba","ab"]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Comparing every pair of words is O(n²). Instead, compute something from each word that is identical for all of its anagrams.

Hint 2

The sorted letters work as that key: "".join(sorted(w)). Append each word to groups[key] in a dictionary of lists.

Hint 3

The key must keep how many times each letter appears: the set of letters would put "aab" and "abb" together.

Solution and why it works
pythonO(n·L log L), n words of length ≤ L · O(n·L)
from collections import defaultdict

def group_by_letters(words: list[str]) -> list[list[str]]:
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)   # anagrams share their sorted letters
    return list(groups.values())

Two words are anagrams exactly when their sorted letters match, so the sorted string is a canonical key: one dictionary lookup per word replaces comparing every pair. The key must be hashable (a string or a tuple, not a list) and must keep the letter counts: keyed by set(word), "aab" and "abb" land in the same group. A tuple of 26 counts as the key avoids the sort: O(L) per word.

Related lab: Loops in motion