Skip to content

Commit 6c80015

Browse files
committed
group anagrams
1 parent 0fe0d36 commit 6c80015

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

49.GroupAnagrams.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
49. Group Anagrams
3+
Medium
4+
Array | Hash Table | String | Sorting
5+
---
6+
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
7+
8+
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
9+
typically using all the original letters exactly once.
10+
11+
Example 1:
12+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
13+
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
14+
15+
Example 2:
16+
Input: strs = [""]
17+
Output: [[""]]
18+
19+
Example 3:
20+
Input: strs = ["a"]
21+
Output: [["a"]]
22+
23+
Constraints:
24+
1 <= strs.length <= 104
25+
0 <= strs[i].length <= 100
26+
strs[i] consists of lowercase English letters.
27+
"""
28+
29+
import collections
30+
from typing import List
31+
32+
33+
# O(m log n) time | O(m) space
34+
class Solution:
35+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
36+
dict = {}
37+
38+
for i in range(len(strs)):
39+
curr = strs[i]
40+
sorted_s = "".join(sorted(curr))
41+
42+
if dict.get(sorted_s):
43+
dict[sorted_s].append(curr)
44+
else:
45+
dict[sorted_s] = [curr]
46+
47+
return dict.values()
48+
49+
50+
# O(m log n) time | O(m) space
51+
class Solution2:
52+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
53+
dict = collections.defaultdict(list)
54+
55+
for s in strs:
56+
count = [0] * 26
57+
58+
for c in s:
59+
count[ord(c) - ord("a")] += 1
60+
61+
dict[tuple(count)].append(s)
62+
63+
return dict.values()

0 commit comments

Comments
 (0)