Skip to content

Commit 39f1241

Browse files
committed
solved group anagram
1 parent bb53e35 commit 39f1241

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

group-anagrams/samthekorean.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# TC : O(nwlog(w))
2+
# reason : n being the number of words and w being the length of each word, therefore the total time complexity is n times wlog(w) (time complexity for sorting each word)
3+
# SC : O(w*n)
4+
from collections import defaultdict
5+
6+
7+
class Solution:
8+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
9+
anagrams = defaultdict(list)
10+
11+
# Use sorted word as a string and append it with the original word so the word containing same charactors with the same number of existence can be in the same group
12+
for word in strs:
13+
anagrams[str(sorted(word))].append(word)
14+
15+
return anagrams.values()

0 commit comments

Comments
 (0)