-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0049--group-anagrams-optimized.js
43 lines (35 loc) · 1.15 KB
/
0049--group-anagrams-optimized.js
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
// 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.
// Examples
// Input: strs = ["eat","tea","tan","ate","nat","bat"]
// Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
// Input: strs = [""]
// Output: [[""]]
// Input: strs = ["a"]
// Output: [["a"]]
// Constraints:
// 1 <= strs.length <= 104
// 0 <= strs[i].length <= 100
// strs[i] consists of lowercase English letters.
/**
* @param {string[]} strs
* @return {string[][]}
*/
const groupAnagrams = (strs) => {
const anagramMap = {};
const charcodeForA = "a".charCodeAt(0);
for (const str of strs) {
const charCount = Array(26).fill(0);
for (let i = 0; i < str.length; i++) {
const countIndex = str.charCodeAt(i) - charcodeForA;
charCount[countIndex]++;
}
const anagramKey = charCount.join(",");
if (anagramKey in anagramMap) {
anagramMap[anagramKey].push(str);
} else {
anagramMap[anagramKey] = [str];
}
}
return Object.values(anagramMap);
};