add group-anagrams
This commit is contained in:
13
0049_group-anagrams/python3/naive.py
Normal file
13
0049_group-anagrams/python3/naive.py
Normal 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())
|
||||
24
0049_group-anagrams/python3/solution.py
Normal file
24
0049_group-anagrams/python3/solution.py
Normal 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())
|
||||
Reference in New Issue
Block a user