Group Anagrams
Master this topic with zero to advance depth.
Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Visual Representation
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
1. Sort each string to create a 'key':
"eat" -> "aet"
"tea" -> "aet"
"tan" -> "ant"
...
2. Group by key in a Hash Map:
"aet" -> ["eat", "tea", "ate"]
"ant" -> ["tan", "nat"]
"abt" -> ["bat"]Examples
"eat", "tea", and "ate" are anagrams. "tan" and "nat" are anagrams. "bat" is alone.
Level I: Brute Force (Compare All Pairs)
Intuition
Compare every string with every other string to check if they are anagrams. We use a used boolean array to keep track of strings that have already been grouped. This is the simplest baseline approach but inefficient for large inputs.
Detailed Dry Run
| String A | String B | Sorted(A) | Sorted(B) | Is Anagram? |
|---|---|---|---|---|
| "eat" | "tea" | "aet" | "aet" | Yes |
| "eat" | "tan" | "aet" | "ant" | No |
| "tan" | "nat" | "ant" | "ant" | Yes |
Level II: Better Solution (HashMap with Sorted String Key)
Intuition
Instead of nested loops, we use a Hash Map. Since all anagrams share the same sorted version, we sort each string and use it as a key. All strings that result in the same sorted string are added to the same list.
Detailed Dry Run
| Input String | Sorted Key | Action |
|---|---|---|
| "eat" | "aet" | Map["aet"] = ["eat"] |
| "tea" | "aet" | Map["aet"] = ["eat", "tea"] |
| "tan" | "ant" | Map["ant"] = ["tan"] |
Level III: Optimal Solution (Frequency Bucket Key)
Intuition
Instead of sorting each string (), we can use the character frequencies (26 characters) as the Hash Map key. This reduces the transformation time to linear . We represent the count array as a string or tuple to use as a key.
Detailed Dry Run
Bucket Count Key
| Char | Frequency Count Array |
|---|---|
| eat | [1, 0, 0, 0, 1, ..., 1, ...] (a:1, e:1, t:1) |
| tea | [1, 0, 0, 0, 1, ..., 1, ...] (same signature) |
Logic: key = "#1#0#0...#1". Anagrams share the same key without ever sorting.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.