Skip to content

Commit 59d537d

Browse files
committed
feat: add Group Anagrams
1 parent 37ce543 commit 59d537d

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

README.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ https://neetcode.io/roadmap
44

55
### Leetcode
66

7-
<!-- create a table for me -->
8-
97
| # | Title | Difficulty | Solution |
108
| --- | ----------------------------------------------------------------------- | ---------- | ---------------------------------------------------- |
119
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | Easy | [TypeScript](./TypeScript/217.contains-duplicate.ts) |
1210
| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | Easy | [TypeScript](./TypeScript/242.valid-anagram.ts) |
1311
| 242 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [TypeScript](./TypeScript/1.two-sum.ts) |
12+
| 49 | [Group Anagrams](https://leetcode.com/problems/two-sum/) | Medium | [TypeScript](./TypeScript/49.group-anagrams.ts) |

TypeScript/49.group-anagrams.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function groupAnagrams(strs: string[]): string[][] {
2+
const map = new Map<string, string[]>();
3+
4+
strs.forEach((s) => {
5+
const identity = new Array(26).fill(0); // it also can be the sorted string
6+
7+
for (let i = 0; i < s.length; i++) {
8+
identity[s.charCodeAt(i) - 97] += 1;
9+
}
10+
11+
const key = identity.join(",");
12+
const anagrams = map.get(key) ?? [];
13+
14+
anagrams.push(s);
15+
map.set(key, anagrams);
16+
});
17+
18+
return Array.from(map.values());
19+
}

0 commit comments

Comments
 (0)