Hash Tables/Practice/Group Anagrams
Group Anagrams - Visual Solution & Python Code
Give every word a canonical fingerprint: its letters sorted (or a 26-slot letter count). Words that are anagrams share the same fingerprint, so use it as a hash map key and push each word into the bucket it lands in.
Why it works
Comparing every pair of words is O(n²). The fingerprint collapses the comparison to a dictionary lookup: one pass to bucket, then the answer falls out of the map. Sorting keys costs O(k log k) per word; the letter-count key makes it O(k).
The problem
Given an array of strings, group the anagrams together. You can return the answer in any order. An anagram is a word formed by rearranging the letters of another word.
Hints
- Two strings are anagrams if and only if their sorted characters are identical.
- Use sorted(word) as a dictionary key (convert to tuple for hashability).
- defaultdict(list) makes grouping clean.
Test cases
| Input | Expected |
|---|---|
group_anagrams(["eat","tea","tan","ate","nat","bat"]) | 3 groups |
group_anagrams([""]) | [[""]] |
Reference starter code
from collections import defaultdict
def group_anagrams(strs):
# Key insight: anagrams have the same sorted characters
pass
print(group_anagrams(["eat","tea","tan","ate","nat","bat"]))
print(group_anagrams([""])) # [[""]]
print(group_anagrams(["a"])) # [["a"]]
More challenges in this topic
Try it yourself
Solve it in the browser editor with real test cases and instant feedback - free, no signup needed.
Next challenge in this topic: Subarray Sum Equals K