Skip to content

Commit fbed708

Browse files
Add No_0049: Group Anagrams
1 parent b82b861 commit fbed708

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'''
2+
3+
Description:
4+
5+
Given an array of strings, group anagrams together.
6+
7+
Example:
8+
9+
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
10+
Output:
11+
[
12+
["ate","eat","tea"],
13+
["nat","tan"],
14+
["bat"]
15+
]
16+
Note:
17+
18+
All inputs will be in lowercase.
19+
The order of your output does not matter.
20+
21+
'''
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
'''
2+
3+
Description:
4+
5+
Given an array of strings, group anagrams together.
6+
7+
Example:
8+
9+
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
10+
Output:
11+
[
12+
["ate","eat","tea"],
13+
["nat","tan"],
14+
["bat"]
15+
]
16+
Note:
17+
18+
All inputs will be in lowercase.
19+
The order of your output does not matter.
20+
21+
'''
22+
23+
24+
25+
from collections import Counter
26+
from collections import defaultdict
27+
from typing import List
28+
class Solution:
29+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
30+
31+
anagram_dict = defaultdict( list )
32+
33+
34+
for s in strs:
35+
36+
ordered_s = ''.join(sorted(s))
37+
38+
anagram_dict[ordered_s].append( s )
39+
40+
return [ anagram_dict[key_string] for key_string in anagram_dict ]
41+
42+
43+
44+
# n : the number of strings in input strs.
45+
# k : the average character length of strings
46+
47+
## Time Complexity: O( n k log k)
48+
#
49+
# The overhead in time is the for loop, iterating on strs, which is of O( n ),
50+
# and the cost of sorted(s), which is of O( k log k ).
51+
# It takes O( n k log k ) in total.
52+
53+
## Space Complexity: O( n )
54+
#
55+
# The overhead in space is the storage for dictionary, anagram_dict, which is of O( n )
56+
57+
58+
from collections import namedtuple
59+
TestEntry = namedtuple('TestEntry', 'input_string')
60+
def test_bench():
61+
62+
test_data = [
63+
TestEntry( input_string = ["eat", "tea", "tan", "ate", "nat", "bat"] )
64+
]
65+
66+
# expected output:
67+
'''
68+
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
69+
'''
70+
71+
for t in test_data:
72+
73+
print( Solution().groupAnagrams( t.input_string) )
74+
75+
return
76+
77+
78+
79+
if __name__ == '__main__':
80+
81+
test_bench()

0 commit comments

Comments
 (0)