Skip to content

Commit 85525d8

Browse files
Update and rename group_anagrams.cpp to group_anagrams.py
1 parent e45c2f1 commit 85525d8

File tree

2 files changed

+49
-32
lines changed

2 files changed

+49
-32
lines changed

group_anagrams.cpp

-32
This file was deleted.

group_anagrams.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// class Solution {
2+
// public:
3+
// vector<vector<string>> groupAnagrams(vector<string>& strs) {
4+
5+
// if(strs.empty()) return {{}};
6+
7+
// map<string, vector<string>> mp;
8+
9+
// for(auto str: strs){
10+
// int cHash[26] = {0};
11+
// for(auto c : str)
12+
// cHash[c-'a']++;
13+
// string st;
14+
// for(auto i : cHash){
15+
// st += to_string(i) + ',';
16+
// }
17+
// mp[st].push_back(str);
18+
// }
19+
20+
// vector<vector<string>> vs;
21+
// vector<string> cvs;
22+
23+
// for(auto& [key, value] : mp){
24+
// for(auto ele : value){
25+
// cvs.push_back(ele);
26+
// }
27+
// vs.push_back(cvs);
28+
// cvs.clear();
29+
// }
30+
// return vs;
31+
// }
32+
// };
33+
34+
35+
class Solution:
36+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
37+
38+
# works only if we have all chars between 'a' => 'z'
39+
# TC: O(m * n * 26)) ==> O(m * n) where m = len(strs), n = max_length_of_string_in_strs
40+
hashmap = defaultdict(list)
41+
42+
for string in strs:
43+
frequency = [0] * 26
44+
for char in string:
45+
frequency[ord(char) - 97] += 1 #97 is ord('a')
46+
47+
hashmap[tuple(frequency)].append(string)
48+
49+
return hashmap.values()

0 commit comments

Comments
 (0)