Skip to content

Commit c751f4d

Browse files
committed
- Group Anagrams DaleStudy#236
1 parent 29d2f61 commit c751f4d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

group-anagrams/ayosecu.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
from collections import defaultdict
3+
4+
class Solution:
5+
"""
6+
- Time Complexity: O(nklogk), n = len(strs), k = Max of len(strs[i])
7+
- for loop => O(n)
8+
- sorted(s) => O(klogk)
9+
- Space Complexity: O(nk), dictionary size
10+
"""
11+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
12+
# dictionary
13+
dic = defaultdict(list)
14+
15+
for s in strs:
16+
ss = "".join(sorted(s))
17+
dic[ss].append(s)
18+
19+
return list(dic.values())
20+
21+
tc = [
22+
(["eat","tea","tan","ate","nat","bat"], [["bat"],["nat","tan"],["ate","eat","tea"]]),
23+
([""], [[""]]),
24+
(["a"], [["a"]])
25+
]
26+
27+
for i, (strs, e) in enumerate(tc, 1):
28+
sol = Solution()
29+
r = sol.groupAnagrams(strs)
30+
r_sorted = sorted([sorted(group) for group in r])
31+
e_sorted = sorted([sorted(group) for group in e])
32+
print(f"TC {i} is Passed!" if r_sorted == e_sorted else f"TC {i} is Failed! - Expected: {e_sorted}, Result: {r_sorted}")

0 commit comments

Comments
 (0)