DSA Visualizer · 25 visualizationsGroup Anagrams
Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. Two strings are anagrams if one is a rearrangement of the other's characters.
Start with an empty map from each word's sorted letters to the words that share them.
Problem
Given an array of strings strs, group the anagrams together. You can return the answer in any order. Two strings are anagrams if one is a rearrangement of the other's characters.
Examples
Constraints
- 1 ≤ strs.length ≤ 10⁴
- 0 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters
Intuition
Anagrams share the same letters, so they also share the same sorted form. Use that sorted form as a key and collect each word under it.
Brute force → Optimal
For each word, compare its sorted form with every other word's sorted form and merge the matches into groups.
Sort each word once to build a key, then append the word to the matching bucket in a hash map.
Complexity
Edge cases
- A single word, e.g. ["a"], forms one group by itself.
- Words with repeated letters, e.g. "aab" and "aba", still share the same sorted key.
- The empty string is its own group when it appears in the input.
Common mistakes
- Not sorting (or otherwise normalizing) the characters before using them as a key.
- Creating a fresh list for every word instead of appending to the existing group.