Skip to content

Commit 46333ca

Browse files
committed
Added improved JS solution for problem 49
1 parent 5356af7 commit 46333ca

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

javascript/49-Group-Anagrams.js

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,58 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Hash Each Word
3+
// Time: O(n*max(w))
4+
// Space: O(n*max(w))
5+
// This solution is faster than sorting each word.
6+
//////////////////////////////////////////////////////////////////////////////
7+
8+
/** @const {!Object<string, number>} */
9+
const CODES = {
10+
a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7, i: 8, j: 9,
11+
k: 10, l: 11, m: 12, n: 13, o: 14, p: 15, q: 16, r: 17,
12+
s: 18, t: 19, u: 20, v: 21, w: 22, x: 23, y: 24, z: 25
13+
};
14+
15+
/**
16+
* @param {string[]} words
17+
* @return {string[][]}
18+
*/
19+
function groupAnagrams(words) {
20+
21+
const map = Object.create(null);
22+
for (const word of words) {
23+
const hash = hashWord(word);
24+
if (!(hash in map)) {
25+
map[hash] = [];
26+
}
27+
map[hash].push(word);
28+
}
29+
30+
const groups = [];
31+
for (const key in map) {
32+
groups.push(map[key]);
33+
}
34+
return groups;
35+
}
36+
37+
/**
38+
* @param {string} word
39+
* @return {string}
40+
*/
41+
function hashWord(word) {
42+
const hash = new Array(26).fill(0);
43+
for (const ch of word) {
44+
++hash[CODES[ch]];
45+
}
46+
return hash.toString();
47+
}
48+
49+
//////////////////////////////////////////////////////////////////////////////
50+
// Sort Each Word
51+
// Time: O(n*max(w)*log(max(w)))
52+
// Space: O(n*max(w))
53+
// This solution is slower than hashing each word.
54+
//////////////////////////////////////////////////////////////////////////////
55+
156
/**
257
* @param {string[]} strs
358
* @return {string[][]}
@@ -8,7 +63,6 @@ const groupAnagrams = (strs) => {
863
for (let i = 0; i < strs.length; i++) {
964
const sorted = strs[i].split("").sort().join("");
1065
//! we are just splitting the string and sorting it and joining it back
11-
console.log(sorted);
1266
if (map.has(sorted)) {
1367
map.get(sorted).push(strs[i]); //! if the map has the sorted string, we push the string into the array
1468
} else {

0 commit comments

Comments
 (0)