09. Group Anagrams
Given an array of strings strs, group the anagrams together in any order.
How It Works & Algorithmic Design
Solves using Hash Map Grouping with Canonical Key Signature:
- Key Signature: Two strings are anagrams if and only if their sorted character representations are identical (e.g.,
"eat"$\to$"aet"and"tea"$\to$"aet"). - Map Setup: Maintain a Hash Map where key =
sortedStringKeyand value =array of original strings. - Grouping: Loop through each string
sinstrs:- Compute
sortedKey = s.split('').sort().join(''). - Append
stomap[sortedKey].
- Compute
- Return: Return
Object.values(map).
Why This Approach Works Best
Sorted string keys group all anagram variants into matching buckets in $O(n \cdot k \log k)$ time, where $n$ is string count and $k$ is max string length.
Example Walkthrough
["eat","tea","tan","ate","nat","bat"]
List of unsorted strings.
"aet": ["eat","tea","ate"] | "ant": ["tan","nat"] | "abt": ["bat"]
Grouped by canonical sorted string key.
[["eat","tea","ate"],["tan","nat"],["bat"]]
Bucketed list of anagram groups.
Answer: Group anagrams using sorted key map
function groupAnagrams(strs) {
const map = {};
for (const s of strs) {
const key = s.split('').sort().join('');
if (!map[key]) map[key] = [];
map[key].push(s);
}
return Object.values(map);
}Use sorted characters as map keys to group anagram words together.
Canonical representation (like sorted character strings) unifies identical frequency structures.
Character count tuples ($26$-length arrays) can optimize key creation to $O(k)$ per word.
Space complexity is $O(n \cdot k)$ to store string references.