Given an array of strings strs
, group the anagrams together. You can return the answer in any order. For example:
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
"bat"
."nat"
and "tan"
are anagrams as they can be rearranged to form each other."ate"
, "eat"
, and "tea"
are anagrams as they can be rearranged to form each other.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.## Group Anagrams
This problem asks us to group an array of strings into sub-arrays, where each sub-array contains strings that are anagrams of each other. Anagrams are words that contain the same characters, but in a different order.
### Naive Solution
The most straightforward approach is to iterate through each string in the input array and compare it with every other string. For each string, we can check if it's an anagram of any of the other strings. This would involve sorting each string and comparing the sorted versions. If two strings have the same sorted version, they are anagrams.
**Code:**
```python
def group_anagrams_naive(strs):
anagram_groups = []
used = [False] * len(strs)
for i in range(len(strs)):
if used[i]:
continue
group = [strs[i]]
used[i] = True
for j in range(i + 1, len(strs)):
if used[j]:
continue
if sorted(strs[i]) == sorted(strs[j]):
group.append(strs[j])
used[j] = True
anagram_groups.append(group)
return anagram_groups
The optimal solution uses a hash map to store the sorted version of each string as the key, and a list of anagrams as the value. This allows us to group anagrams in a single pass through the input array.
Algorithm:
Code:
def group_anagrams(strs):
anagram_map = {}
for s in strs:
sorted_s = ''.join(sorted(s))
if sorted_s in anagram_map:
anagram_map[sorted_s].append(s)
else:
anagram_map[sorted_s] = [s]
return list(anagram_map.values())
strs = ["eat","tea","tan","ate","nat","bat"]
result = group_anagrams(strs)
print(result) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Code to handle empty input:
def group_anagrams(strs):
if not strs:
return []
anagram_map = {}
for s in strs:
sorted_s = ''.join(sorted(s))
if sorted_s in anagram_map:
anagram_map[sorted_s].append(s)
else:
anagram_map[sorted_s] = [s]
return list(anagram_map.values())