Skip to the workspace
Pebellslearn by building
Arrays & Hashing  ›  Lesson

Canonical Keys: Grouping Things That Match

Group Anagrams 12 minTo group items that are equivalent in some way, turn each one into a canonical key that every member of its group shares and no outsider produces, then collect items by key in a dictionary.

leetcode / Canonical Keys: Grouping Things That Match

Explore each scene at your own pace.

01 · The rule

The rule

Canonical Keys: Grouping Things That Match

A word-puzzle app has a big list of words and wants to show them in families: every family holds words that are rearrangements of one another, like "stop", "pots" and "tops". Comparing every word with every other word would be slow and messy. Instead, give each word a label that all its relatives share, and let a dictionary do the sorting into families.

The rule

Give every item a fingerprint; equal fingerprints share a bucket.

The fingerprint is called a canonical key: one standard form that every member of a group turns into, and no outsider does. For rearranged words, sorting the letters works, because "stop", "pots" and "tops" all sort to "opst".

from collections import defaultdict

def families(words):
    groups = defaultdict(list)        # key -> words with that key
    for word in words:
        key = "".join(sorted(word))
        groups[key].append(word)
    return list(groups.values())

families(["pots", "stop", "note", "cab", "tops", "tone"])
# [['pots', 'stop', 'tops'], ['note', 'tone'], ['cab']]

The whole skill is choosing the key. It must pass two tests: every member produces the same key, and no non-member produces it. Some keys that pass:

  • Rearranged words: the sorted letters, or a tuple of 26 letter counts.
  • Emails that differ only in capital letters: email.lower().
  • Phone numbers typed in different styles: only the digits, "".join(ch for ch in phone if ch.isdigit()).

A key must also be hashable to live in a dictionary. Strings, numbers and tuples are fine; a list is not, so turn counts into a tuple before using them as a key.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.