Skip to content

Commit 99c7c92

Browse files
committed
solve: group anagrams
1 parent b663600 commit 99c7c92

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

group-anagrams/evan.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {string[]} strList
3+
* @return {string[][]}
4+
*/
5+
var groupAnagrams = function (strList) {
6+
const map = new Map();
7+
8+
for (const str of strList) {
9+
const sortedStr = str.split("").sort().join("");
10+
11+
if (!map.has(sortedStr)) {
12+
map.set(sortedStr, []);
13+
}
14+
15+
map.get(sortedStr).push(str);
16+
}
17+
18+
return Array.from(map.values());
19+
};
20+
21+
/**
22+
* Time Complexity: O(n * k log k)
23+
* Reason:
24+
* - n is the number of strings in the input array.
25+
* - k is the maximum length of a string in the input array.
26+
* - Sorting each string takes O(k log k) time.
27+
* - Thus, sorting all n strings takes O(n * k log k) time.
28+
*
29+
* Space Complexity: O(n * k)
30+
* Reason:
31+
* - We use a map to store the grouped anagrams.
32+
* - In the worst case, we might store all n strings in the map.
33+
* - Each string has a maximum length of k.
34+
* - Thus, the space complexity is O(n * k).
35+
*/

0 commit comments

Comments
 (0)