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
+
1
56
/**
2
57
* @param {string[] } strs
3
58
* @return {string[][] }
@@ -8,7 +63,6 @@ const groupAnagrams = (strs) => {
8
63
for ( let i = 0 ; i < strs . length ; i ++ ) {
9
64
const sorted = strs [ i ] . split ( "" ) . sort ( ) . join ( "" ) ;
10
65
//! we are just splitting the string and sorting it and joining it back
11
- console . log ( sorted ) ;
12
66
if ( map . has ( sorted ) ) {
13
67
map . get ( sorted ) . push ( strs [ i ] ) ; //! if the map has the sorted string, we push the string into the array
14
68
} else {
0 commit comments