Group Anagrams Problem
Description
LeetCode Problem 49.
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
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"]]
Constraints:
- 1 <= strs.length <= 10^4
- 0 <= strs[i].length <= 100
- strs[i] consists of lowercase English letters.
Solution
Approach: Hash Map Keyed by Sorted Letters
Two words are anagrams exactly when they contain the same letters the same number of times, which is the same as saying their letters, once sorted, give the same string: "eat", "tea" and "ate" all become "aet". That sorted string is a key every word in a group shares and no word outside it has.
- Create a hash map from key to the list of words with that key.
- For each word, sort its letters to get the key and append the word to that key's list.
- Return the lists in the map.
Comparing every pair of words instead would take O(n2) comparisons; with the map each word is handled once.
Empty strings need no special case: "" sorts to "", so all empty strings land in one group, as in [""] -> [[""]].
Duplicates also need no special case: "abc" appearing twice puts both copies in the same group, which is what the problem expects.
Complexity: O(n · k log k) time and O(n · k) space, where n is the number of strings and k is the length of the longest one (sorting each word costs O(k log k), and the map stores every character once).
import collections
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = collections.defaultdict(list) # sorted letters -> the words made of them
for word in strs:
key = "".join(sorted(word)) # anagrams have the same sorted letters
groups[key].append(word)
return list(groups.values())