Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
There is no string in strs that can be rearranged to form "bat". The strings "nat" and "tan" are anagrams as they can be rearranged to form each other. The strings "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.
from collections import defaultdict
def groupAnagrams(strs):
"""Groups anagrams together in a list of strings.
Args:
strs (list[str]): A list of strings.
Returns:
list[list[str]]: A list of lists, where each inner list contains anagrams.
"""
anagram_groups = defaultdict(list)
for s in strs:
# Use a sorted string as the key for anagrams
key = "".join(sorted(s))
anagram_groups[key].append(s)
return list(anagram_groups.values())
# Example usage
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
result = groupAnagrams(strs)
print(result) # Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
defaultdict
is used to store anagrams. The keys are sorted strings, and the values are lists of strings that are anagrams of each other.anagram_groups
dictionary.anagram_groups
dictionary to a list and return it.A brute force solution would involve comparing each string with every other string to check if they are anagrams. This is inefficient.
def groupAnagrams_brute_force(strs):
if not strs:
return []
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 not used[j] and is_anagram(strs[i], strs[j]):
group.append(strs[j])
used[j] = True
groups.append(group)
return groups
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
# Example usage:
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(groupAnagrams_brute_force(strs))
Optimal Solution:
Brute Force Solution:
Optimal Solution:
anagram_groups
dictionary.Brute Force Solution: