Medium Sorted Key Hash Maps
In plain English: Group words that contain the exact same letters, like 'eat' and 'tea'.
Anagrams share the same sorted character sequence — use that as a hashmap key to bucket them together.
Prompt
Group a list of words by anagram.
Try to write it from scratch before scrolling down.
Solution
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
key = tuple(sorted(w)) # sorted chars = canonical key
groups[key].append(w)
return list(groups.values())
# Test: group_anagrams(["eat","tea","tan","ate","nat","bat"])
# => [["eat","tea","ate"], ["tan","nat"], ["bat"]]