25 lines
744 B
Python
25 lines
744 B
Python
|
# Time: O(N · M)
|
||
|
# Space: O(N)
|
||
|
|
||
|
from collections import Counter, defaultdict
|
||
|
|
||
|
class Solution:
|
||
|
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
|
||
|
# If key doesn't exist, creates empty list using `list`
|
||
|
# factory/ctor function
|
||
|
groups = defaultdict(list)
|
||
|
|
||
|
for s in strs:
|
||
|
# Keep counter for num of times each letter appeared
|
||
|
counts = [0] * 26
|
||
|
|
||
|
for c in s:
|
||
|
i = ord(c) - ord('a')
|
||
|
counts[i] += 1
|
||
|
|
||
|
# Lists aren't hashable, so we need to convert the counts
|
||
|
# to tuple so that we can key them
|
||
|
groups[tuple(counts)].append(s)
|
||
|
|
||
|
return list(groups.values())
|