add group-anagrams

This commit is contained in:
2022-04-21 14:16:42 +05:30
parent 1578bc52d6
commit 25fe22ae23
3 changed files with 64 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
# Time: O(N * MlogM) where N is len(strs) and M is num of chars in a string
# Space: O(N)
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = {}
for s in strs:
s_sorted = ''.join(sorted(s))
groups[s_sorted] = groups.get(s_sorted, []) + [s]
return list(groups.values())

View File

@@ -0,0 +1,24 @@
# 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())