Sort each word as the map key
Anagrams share a sorted signature. Bucket words by sorted(word).
eat, tea, ate all sort to aet. One hash map from signature → list is the whole algorithm.
Algorithm
- For each word, sort its letters to get a key.
- Append the word to that key's bucket.
- Return the buckets.
- Time
- O(n k log k)
- Space
- O(n k)
class Solution: def groupAnagrams(self, words: list[str]) -> list[list[str]]: groups: dict[str, list[str]] = {} for w in words: key = "".join(sorted(w)) groups.setdefault(key, []).append(w) return list(groups.values())