Skip to content

Commit 4230e0b

Browse files
committed
add solution for grouping anagrams
1 parent f1aa488 commit 4230e0b

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

โ€Žgroup-anagrams/gcount85.pyโ€Ž

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
# Approach
3+
strs ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ๋ฌธ์ž์—ด์„ ์ •๊ทœํ™”(์ •๋ ฌ)ํ•˜๊ณ ,
4+
์ •๊ทœํ™” ๊ฐ’์ด ๊ฐ™์€ ์›์†Œ๋“ค๋ผ๋ฆฌ ๋ชจ์ด๋„๋ก ๋”•์…”๋„ˆ๋ฆฌ์— ์ถ”๊ฐ€ํ•˜์—ฌ ์ตœ์ข… ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
5+
6+
# Complexity
7+
strs์˜ ๊ธธ์ด๋ฅผ N, ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ K๋ผ๊ณ  ํ•  ๋•Œ,
8+
9+
- Time complexity: O(N*KlogK)
10+
- Space complexity: O(N*K)
11+
"""
12+
13+
from collections import defaultdict
14+
15+
16+
class Solution:
17+
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
18+
anagram = defaultdict(list) # normalized str : str list
19+
for s in strs:
20+
anagram["".join(sorted(s))].append(s)
21+
return list(anagram.values())

0 commit comments

Comments
ย (0)