Home
DSA Patterns
Hash Map
Group Anagrams
Group Anagrams
Group words that are anagrams of each other, using each word's sorted letters as a hash map key.
Problem Understanding
Group Anagrams: given an array of strings strs, group the words that are anagrams of each other. The groups, and the words inside them, may be returned in any order.
Example: ["eat", "tea", "tan", "ate", "nat", "bat"] returns [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].
Attempt 1: Compare Every Pair
For each word not yet grouped, compare it with every later word using an anagram check and pull the matches into its group. That is O(n²) anagram checks. The pairwise comparison is the waste: if each word could be turned into a label that all of its anagrams share, words could be sorted into buckets directly.
The Intuition: A Key Every Anagram Shares
Sort a word's letters and every anagram of it produces the same string: "eat", "tea" and "ate" all sort to "aet". Use that string as a hash map key:
- For each word, compute
key = sorted(word). - If
keyis new, start an empty list for it. - Append the word to
key's list.
One pass, no pairwise comparisons — the map does the matching. It is the same counting idea as Valid Anagram, turned into a key.
Interactive Walkthrough
["eat", "tea", "tan", "ate", "nat", "bat"]
START
groups (key → words)
empty
Key
—
Groups
0
groups starts empty: each key will map to the list of words that share it
Next
"eat" sorts to "aet" — every anagram of "eat" sorts to the same key
Words
The words run along the top with each one's sorted key under it. Below them, the map: one row per key, collecting its words as they arrive. Watch "tea" and "ate" land in the row "eat" started.
