Guild of Anagrams: Group Words
๐ฆ Guild of Anagrams: Group Words
Difficulty: Intermediate Tags: hashmap, strings, sorting, grouping Series: CS 102: Problem Solving & Logic
Problem
In the mystical Guild of Anagrams, words with the same letters belong to the same group, regardless of order. Your task is to group a list of words by their anagram relationships.
Two words are anagrams if they contain the exact same letters with the same frequencies, just in different orders. For example, "eat", "tea", and "ate" are all anagrams of each other.
Given a list of words, return groups where each group contains all words that are anagrams of each other.
Real-World Application
Anagram grouping appears in: - Spell checkers - suggesting alternative spellings - Word games - Scrabble, Words with Friends, anagram puzzles - Plagiarism detection - finding text variations - Code refactoring tools - identifying similar variable names - Search engines - query expansion and typo correction
Input
data = list[str] # List of lowercase words
Output
list[list[str]] # Groups of anagrams (order doesn't matter)
Constraints
- Total words โค 100,000
- Each word contains only lowercase letters a-z
- Words can be empty strings
- Groups can be returned in any order
- Words within groups can be in any order
Examples
Example 1: Mixed Anagrams
Input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Explanation: - "eat", "tea", "ate" all have letters {a:1, e:1, t:1} โ same group - "tan", "nat" both have letters {a:1, n:1, t:1} โ same group - "bat" has unique letters {a:1, b:1, t:1} โ solo group
Example 2: No Anagrams
Input: ['a', 'b', 'c']
Output: [['a'], ['b'], ['c']]
Explanation: No words share the same letters, so each word is its own group.
Example 3: All Same Anagrams
Input: ['abc', 'bca', 'cab', 'bac']
Output: [['abc', 'bca', 'cab', 'bac']]
Explanation: All four words are anagrams of each other.
What You'll Learn
- Creating canonical keys for grouping (sorted strings or character counts)
- Using hashmaps for efficient grouping
- The trade-off between sorting and counting approaches
- How to handle edge cases (empty strings, duplicates)
Why This Matters
Interviews frequently test your ability to recognize when to use hashing, understand canonicalization, and analyze time/space complexity trade-offs.