Algorithms · Level 2 Hash Maps

Anagram Groups with a Dict

Group the words of a word game that use the same letters in one pass, with a dict keyed by the sorted letters instead of comparing every pair.

  • group by a computed key
  • setdefault(key, []).append(item)
  • lists can't be dict keys

A dict can group items by a computed key: items with the same key land in the same list, in one pass. Trap: a list can't be a dict key; turn sorted(word) into a string or a tuple first.

groups = {}
for w in ["hi", "yes", "no"]:
    groups.setdefault(len(w), []).append(w)
groups  # {2: ['hi', 'no'], 3: ['yes']}

Write group_anagrams(words): lists of words that use exactly the same letters, groups in order of first appearance, words in input order. Example: group_anagrams(['ward', 'draw', 'note', 'tone', 'warp']) → [['ward', 'draw'], ['note', 'tone'], ['warp']].

solution.py
Test Suites Pending
Output