leetcode/0049_group-anagrams/python3/solution.py

25 lines
744 B
Python
Raw Normal View History

2022-04-21 08:46:42 +00:00
# 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())