0:00 / 0:00

Group words that are anagrams of each other. Sort each word's letters into a key, then file every word under its key in a hash map.

▼

The problem

LeetCode 49 (Medium). Given a list of strings, group the anagrams together (words made of exactly the same letters, in any order). The groups can come back in any order.

Example: ["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]].

def groupAnagrams(strs):
    groups = {}                    # key -> list of words
    for word in strs:
        key = ''.join(sorted(word))    # 'eat' -> 'aet'
        groups.setdefault(key, []).append(word)
    return list(groups.values())
TRY IT ON LEETCODE ▶

The solution

def groupAnagrams(strs):
    groups = {}                    # key -> list of words
    for word in strs:
        key = ''.join(sorted(word))    # 'eat' -> 'aet'
        groups.setdefault(key, []).append(word)
    return list(groups.values())

Transcript

Group Anagrams. You get a list of words. Group the anagrams together: words made of exactly the same letters, in any order. Eat and tea are anagrams: the same three letters, shuffled.

Take eat, tea, tan, ate, nat and bat. Eat, tea and ate share one group. Tan and nat make a second. Bat has no partner, so it sits alone. Three groups, in any order.

The naive way compares every pair of words, checking whether their letters match. Six words make fifteen pairs. Twelve would make sixty six. The work grows with the square of the list.

Instead, give every word a label that all its anagrams share. Sort its letters. Eat becomes A, E, T. Tea becomes A, E, T. Ate becomes A, E, T too. Anagrams always sort to the same word, and other words never do. That sorted word is the key.

Now picture a hash map as a wall of pigeonholes in a mail room. Each slot is labeled with a key and holds a list of words. Finding a key's slot is one quick lookup, however many slots there are.

Let's sort the mail. Eat becomes A, E, T: there's no slot yet, so open one. Tea has the same key: same slot. Tan becomes A, N, T: a second slot. Ate joins the first. Nat joins the second. Bat becomes A, B, T and opens a third. Three groups, in one pass.

In code, start with an empty dictionary. For each word, sort its letters and join them into a string: that's the key. Append the word to that key's list, starting a new list if the key is new. Finally, return the lists.

Each of the n words is sorted once. Sorting k letters costs k log k, so the time is n times k log k. The map stores every letter once, so the space is n times k. Counting the twenty six letters instead builds each key in order k time.

Sort the letters, find the slot, drop it in. That's Group Anagrams.