Group Anagrams
Problem
Given an array of strings
strs, group the anagrams together. You can return the answer in any order.
Examples
Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2
Input: strs = [""]
Output: [[""]]
Example 3
Input: strs = ["a"]
Output: [["a"]]
Key Insight
All anagrams share the same "signature."
To group anagrams, use a canonical form (sorted or char-count) as hash key.
How to Approach This Problem
Pattern Recognition: When you see keywords like
group anagrams arrays-and-hashing,
think Hash Set / Hash Map.
Step-by-Step Reasoning
1
What's the main challenge in grouping anagrams?
Answer: Finding a way to identify which strings are anagrams
We need a method to determine "these strings belong together" without comparing every pair (which would be O(n²)).
2
What property is IDENTICAL for all anagrams of the same word?
Answer: Sorted character sequence
Sorting the characters produces the same result for all anagrams. "eat"→"aet", "tea"→"aet". This sorted form is called a signature - a canonical representation that's identical for all anagrams of the same word. Length is necessary but not sufficient (many non-anagrams have same length).
3
To group strings by their signature, what data structure is best?
Answer: Hash map: signature → list of strings
We need to map each signature to all strings that share it. Hash map gives O(1) lookup by signature, and stores the list of matching strings.
4
What is the time complexity difference between sorted vs count signatures?
Answer: Sorted: O(k log k) per string. Count: O(k) per string
For string of length k, sorting is O(k log k), counting is O(k). For very long strings, counting is faster. For short strings, difference is negligible.
5
After processing all strings, the hash map values are:
Answer: The groups of anagrams
The map is signature → [list of strings with that signature]. The values are exactly the groups we need to return.
Solution
def groupAnagrams(strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for s in strs:
# Use sorted string as signature
key = ''.join(sorted(s))
groups[key].append(s)
return list(groups.values())
Complexity Analysis
| Time | O(n * k log k) |
|---|---|
| Space | O(n * k) |
Master This Pattern
Build intuition with interactive MCQs. Practice Hash Set / Hash Map problems in the LeetEye app.
Download LeetEye Free