Group Anagrams
HashingString
MediumLeetCode #49
Problem Statement
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.
Example
Input Array:
"eat"
"tea"
"tan"
"ate"
"nat"
"bat"
↓
Grouped Anagrams:
Key: "aet"
"eat"
"tea"
"ate"
Key: "ant"
"tan"
"nat"
Key: "abt"
"bat"
Group 1: "aet"
Group 2: "ant"
Group 3: "abt"
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
- "eat", "tea", "ate" are anagrams (same letters: a, e, t)
- "tan", "nat" are anagrams (same letters: a, n, t)
- "bat" has unique letters and forms its own group
Key Insights
- • Anagrams have the same characters with the same frequency
- • Sorting characters creates a unique key for each anagram group
- • Hash map can efficiently group strings by their sorted key
- • Time complexity: O(n * m log m) where n is number of strings, m is average length
- • Alternative: Use character frequency count as key
Constraints
- • 1 ≤ strs.length ≤ 10^4
- • 0 ≤ strs[i].length ≤ 100
- • strs[i] consists of lowercase English letters only
Algorithm Explanation
This solution uses a hash map to group anagrams efficiently. The key insight is that anagrams have the same characters with the same frequencies, so we can create a unique key for each anagram group.
Key Steps
- Create Key: Sort characters of each string to create a unique key.
- Group by Key: Use hash map to group strings with the same key.
- Collect Groups: Extract all groups from the hash map.
- Return Result: Return the grouped anagrams as a list of lists.
Algorithm Analysis
- Time Complexity: O(n × m log m) where n is the number of strings and m is the average length
- Space Complexity: O(n × m) for storing the hash map and result
- Sorting: Each string needs to be sorted to create the key
- Alternative: Use character frequency counting for O(n × m) time
Group Anagrams Visualization
Step-by-step grouping of anagram strings
Input Array:
"eat"
0
"tea"
1
"tan"
2
"ate"
3
"nat"
4
"bat"
5
Hash Map (Key → Anagrams)
Hash map is empty
Start: Initialize hash map
Starting to group anagrams using hash map
Step 1 of 20
Currently Processing
Processed
Pending
Code Example