Skip to content

Commit 1e90ed0

Browse files
committed
refactor: 49. Group Anagrams
1 parent 040d1c5 commit 1e90ed0

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

group-anagrams/gwbaik9717.js

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// n: length of strs, m: length of strs[i]
2-
// Time complexity: O(nmlogm)
2+
// Time complexity: O(nm)
33
// Space complexity: O(n)
44

55
/**
@@ -10,21 +10,29 @@ var groupAnagrams = function (strs) {
1010
const answer = [];
1111
const anagramDict = new Map();
1212

13-
const sortedStrs = strs.map((str) => {
14-
const splitted = str.split("");
15-
splitted.sort();
16-
return splitted.join("");
17-
});
13+
const getKey = (str) => {
14+
const counter = Array.from(
15+
{ length: "z".charCodeAt() - "a".charCodeAt() + 1 },
16+
() => 0
17+
);
1818

19-
for (let i = 0; i < sortedStrs.length; i++) {
20-
const sortedStr = sortedStrs[i];
21-
const originalStr = strs[i];
19+
for (const chr of str) {
20+
const index = chr.charCodeAt() - "a".charCodeAt();
21+
counter[index]++;
22+
}
23+
24+
return counter.join("#");
25+
};
26+
27+
for (let i = 0; i < strs.length; i++) {
28+
const str = strs[i];
29+
const key = getKey(str);
2230

23-
if (!anagramDict.has(sortedStr)) {
24-
anagramDict.set(sortedStr, []);
31+
if (!anagramDict.has(key)) {
32+
anagramDict.set(key, []);
2533
}
2634

27-
anagramDict.get(sortedStr).push(originalStr);
35+
anagramDict.get(key).push(str);
2836
}
2937

3038
for (const [_, value] of anagramDict) {

0 commit comments

Comments
 (0)