-
Notifications
You must be signed in to change notification settings - Fork 0
/
group-anagrams.ts
59 lines (50 loc) · 1.32 KB
/
group-anagrams.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
typically using all the original letters exactly once.
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
*/
const EXAMPLES = [
{
input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'],
output: [['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']],
},
{
input: [''],
output: [['']],
},
{
input: ['a'],
output: [['a']],
},
];
/** Time O(n log n) | Space O(n) */
function groupAnagrams(words: string[]) {
// S O(n)
const map = new Map<string, string[]>();
// T O(n)
for (const word of words) {
// T O(n log n)
const sortedWord = word.split('').sort().join('');
if (!map.has(sortedWord)) {
map.set(sortedWord, []);
}
map.get(sortedWord)?.push(word);
}
return Array.from(map.values());
}
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('Sorted Map', () => {
EXAMPLES.forEach((example) => {
expect(
groupAnagrams(example.input)
.map((group) => group.sort())
.sort(),
).toEqual(example.output.map((group) => group.sort()).sort());
});
});
}