Skip to content

Commit 0e438e4

Browse files
committed
group-anagrams
1 parent d4cc857 commit 0e438e4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

group-anagrams/taewanseoul.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 49. Group Anagrams
3+
* Given an array of strings strs, group the anagrams together. You can return the answer in any order.
4+
*
5+
* https://leetcode.com/problems/group-anagrams/description/
6+
*/
7+
8+
// O(n * mlog(m)) time
9+
// O(n) space
10+
function groupAnagrams(strs: string[]): string[][] {
11+
const result: string[][] = [];
12+
const map = new Map<string, string[]>();
13+
14+
for (let i = 0; i < strs.length; i++) {
15+
const word = strs[i];
16+
const sorted = word.split("").sort().join("");
17+
18+
if (map.has(sorted)) {
19+
map.get(sorted)!.push(word);
20+
} else {
21+
map.set(sorted, [word]);
22+
}
23+
}
24+
25+
map.forEach((v) => result.push(v));
26+
27+
return result;
28+
}

0 commit comments

Comments
 (0)