Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
- 1 <= strs.length <= 10⁴
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters only
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]strs = [""][[""]]strs = ["a"][["a"]]Grouping anagrams is a bucketing problem. We want to organize a list of strings so that every word made from the same set of characters ends up in the same group.
The most naive way is to compare every word with every other word to check if they are anagrams. For each match, we add the word to the corresponding group. This is extremely slow for large lists.
# Theoretical approach:
groups = []
for word in strs:
found = False
for group in groups:
if is_anagram(word, group[0]):
group.append(word)
found = True
break
if not found: groups.append([word])To group items efficiently, we need a way to make scrambled versions of the same word (like "eat", "tea", "ate") look identical. The core insight is to generate a Canonical Fingerprint (a unique key) for each word. If we sort the letters of "eat", "tea", and "ate", they all become "aet" — our perfect key for a Hash Map.
We iterate through the list exactly once. For each word, we sort its characters to create a key and store the original word in a Hash Map under that key.
groups = {}
for s in strs:
# Use the sorted string as a unique key
key = "".join(sorted(s))
if key not in groups:
groups[key] = []
groups[key].append(s)
return list(groups.values())anagram grouping
Ready to group anagrams from the input list.