from collections import defaultdict
class Solution:
# time O(NWlgW), where N is length of strs, space O(NW)
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list)
res = []
for str in strs:
k = tuple(sorted(str))# or "".join(sorted(str))
d[k].append(str)# note here can't use list ,set as key since they are mutable; instead, we can use tuple() and frozenset() to convert them into valid key since they are immutable
# can be optimized to code in next example
for k,vlist in d.items():
res.append(vlist)
return res
optimization: main idea(use bucket sort as key to identify anagram without sorting)– instead of sorting, use array of size 26 to cnt all chars in the string, and use fixed length of array as identical property to create a valid key(using tuple, not list )
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# time O(NW) space O(26*N)
d = defaultdict(list)
res = []
for str in strs:
cnt = [0]*26
for ch in str:
cnt[ord(ch) - ord('a')] += 1
d[tuple(cnt)].append(str)
return d.values() # since defaultdict(list) return nested list