-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup-anagrams.ts
More file actions
39 lines (36 loc) · 1.15 KB
/
Copy pathgroup-anagrams.ts
File metadata and controls
39 lines (36 loc) · 1.15 KB
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
/**
* 49. Group Anagrams (Medium)
* Link: https://leetcode.com/problems/group-anagrams/
*
* Given an array of strings, group the anagrams together. The order of the
* groups and of the strings within a group does not matter.
*
* Example:
* Input: ["eat","tea","tan","ate","nat","bat"]
* Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
*
* Approach:
* Anagrams share the same 26-letter frequency signature. Build a key from the
* per-letter counts (cheaper and more robust than sorting for long words) and
* bucket each word under its key in a map.
*
* Time: O(n * k) — n words, k = max word length (to build each key).
* Space: O(n * k) — all words stored across the buckets.
*/
export function groupAnagrams(strs: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const word of strs) {
const counts = new Array(26).fill(0);
for (const ch of word) {
counts[ch.charCodeAt(0) - 97]++;
}
const key = counts.join("#");
const bucket = groups.get(key);
if (bucket) {
bucket.push(word);
} else {
groups.set(key, [word]);
}
}
return [...groups.values()];
}