-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnc-ArrayHash-GroupAnagrams.py
More file actions
67 lines (49 loc) · 1.81 KB
/
nc-ArrayHash-GroupAnagrams.py
File metadata and controls
67 lines (49 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
'''
Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Example 1:
Input: strs = ["act","pots","tops","cat","stop","hat"]
Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]]
Example 2:
Input: strs = ["x"]
Output: [["x"]]
Example 3:
Input: strs = [""]
Output: [[""]]
Constraints:
1 <= strs.length <= 1000.
0 <= strs[i].length <= 100
strs[i] is made up of lowercase English letters.
Recommended Time & Space Complexity
You should aim for a solution with O(m * n) time and O(m) space, where m is the number of strings and n is the length of the longest string.
for each item in the list:
check if item.sorted() is an key in the dictionary
if not, add the pair item.sorted():[item] to the dictionary
if yes, add, still add item.sorted():[item] to the dictionary?
for each key in dictionary
add dictionary[key] to list
return list
'''
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
# Build dictionary of grouped anagrams
anagramDict: dict = defaultdict(list)
for str in strs:
anagramKey = "".join(sorted(str))
anagramDict[anagramKey].extend([str])
anagramGroups: list = []
for key in anagramDict:
anagramGroups.append(anagramDict[key])
return anagramGroups
# strs = ["act", "pots", "tops", "cat", "stop", "hat"]
# Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]]
# strs = ["x"]
# Output: [["x"]]
strs = [""]
# Output: [[""]]
solution = Solution()
result = solution.groupAnagrams(strs)
print("The final result is:")
print(result)