09. Group Anagrams

Difficulty:MediumPattern:Hash Map BucketingTime:O(n * k log k)Space:O(n * k)

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:

  1. 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").
  2. Map Setup: Maintain a Hash Map where key = sortedStringKey and value = array of original strings.
  3. Grouping: Loop through each string s in strs:
    • Compute sortedKey = s.split('').sort().join('').
    • Append s to map[sortedKey].
  4. 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

Input

["eat","tea","tan","ate","nat","bat"]

List of unsorted strings.

Key Groups

"aet": ["eat","tea","ate"] | "ant": ["tan","nat"] | "abt": ["bat"]

Grouped by canonical sorted string key.

Output

[["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.

Key Takeaways
  • 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.