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.
Constraints:
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
Example:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Solution
Approach: Using a Hash Map (Dictionary)
The core idea is that anagrams will have the same characters, just in a different order. If we can transform each string into a canonical form that is identical for all its anagrams, we can use this form as a key in a hash map to group them.
- Canonical Form: The simplest canonical form for a string is its characters sorted alphabetically. For example, "eat", "tea", and "ate" all become "aet" when sorted.
- Hash Map: We will use a hash map where:
- Keys: The sorted version of a string (the canonical form).
- Values: A list of all original strings that produce this canonical key.
Steps:
- Initialize an empty hash map (e.g.,
defaultdict(list)in Python orHashMap<String, List<String>>in Java). This map will store the sorted string as the key and a list of original strings as its value.2. Iterate through eachwordin the input arraystrs. - For each
word:- Convert the
wordinto a character array or list of characters. - Sort these characters alphabetically.
- Convert the sorted characters back into a string. This is our
key(the canonical form).
- Convert the
- Add the original
wordto the list associated with thiskeyin the hash map. If thekeydoesn't exist yet, a new list will be created for it. - After iterating through all words, the values of the hash map will be lists of anagrams. Return all these lists.
Python Code Solution:
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
# Use a defaultdict where the default value for a new key is an empty list
anagram_map = defaultdict(list)
for word in strs:
# Sort the characters of the word to create a canonical key
# e.g., "eat" -> "aet", "tea" -> "aet", "tan" -> "ant"
sorted_word_tuple = tuple(sorted(word)) # Using tuple for immutability as dict key
# Append the original word to the list associated with its canonical key
anagram_map[sorted_word_tuple].append(word)
# The values of the map are the groups of anagrams
return list(anagram_map.values())