Skip to content

Commit 33c7218

Browse files
committed
feat: group-anagrams
1 parent 1acede5 commit 33c7218

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

group-anagrams/dusunax.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
# 49. Group Anagrams
3+
4+
use **hash map** to solve the problem.
5+
6+
## Time and Space Complexity
7+
```
8+
TC: O(N * K * Log(K))
9+
SC: O(N * K)
10+
```
11+
12+
## TC is O(N * K * Log(K)):
13+
- iterating through the list of strings and sorting each string. = O(N * K * Log(K))
14+
15+
## SC is O(N * K):
16+
- using a hash map to store the sorted strings. = O(N * K)
17+
'''
18+
class Solution:
19+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
20+
result = defaultdict(list)
21+
22+
for str in strs: # TC: O(N)
23+
sorted_key = ''.join(sorted(str)) # sorting 👉 TC: O(K * Log(K))
24+
result[sorted_key].append(str) # TC: O(1) on average
25+
26+
return list(result.values())

0 commit comments

Comments
 (0)