Skip to content

Commit 5d9fc46

Browse files
committed
solve: group anagrams
1 parent c7fb410 commit 5d9fc46

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

group-anagrams/tolluset.ts

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/* n: strs.length, m: strs.mean
2+
* TC: O(n * m * logm)
3+
* SC: O(n * m)
4+
* */
5+
function groupAnagramsV2(strs: string[]): string[][] {
6+
const map: { [key: string]: string[] } = {};
7+
8+
const strSort = (str: string) => str.split("").sort().join("");
9+
10+
for (const str of strs) {
11+
const sortedStr = strSort(str);
12+
13+
if (map[sortedStr]) {
14+
map[sortedStr].push(str);
15+
} else {
16+
map[sortedStr] = [str];
17+
}
18+
}
19+
20+
return Object.values(map);
21+
}
22+
23+
const tc1V2 = groupAnagramsV2(["eat", "tea", "tan", "ate", "nat", "bat"]); // [["bat"],["nat","tan"],["ate","eat","tea"]]
24+
console.info("🚀 : tolluset.ts:19: tc1V2=", tc1V2);
25+
26+
/**
27+
* @FAILED - Time Limit Exceeded
28+
* TC: O(n^2)
29+
* SC: O(n)
30+
*/
31+
function groupAnagrams(strs: string[]): string[][] {
32+
const n = strs.length;
33+
34+
const res: string[][] = [];
35+
36+
const strSort = (str: string) => str.split("").sort().join("");
37+
38+
for (let i = 0; i < n; i++) {
39+
const bucket: string[] = [];
40+
const cur = strs[i];
41+
42+
if (cur === "#") {
43+
continue;
44+
}
45+
46+
bucket.push(cur);
47+
48+
const sortedCur = strSort(cur);
49+
50+
for (let j = i + 1; j < n; j++) {
51+
const tmpSortedStr = strSort(strs[j]);
52+
53+
if (tmpSortedStr === "#") {
54+
continue;
55+
}
56+
57+
if (sortedCur === tmpSortedStr) {
58+
bucket.push(strs[j]);
59+
strs[j] = "#";
60+
}
61+
}
62+
63+
strs[i] = "#";
64+
65+
res.push(bucket);
66+
}
67+
68+
return res;
69+
}
70+
71+
const tc1 = groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); // [["bat"],["nat","tan"],["ate","eat","tea"]]
72+
console.info("🚀 : tolluset.ts:7: tc1=", tc1);

0 commit comments

Comments
 (0)