11// n: length of strs, m: length of strs[i]
2- // Time complexity: O(nmlogm )
2+ // Time complexity: O(nm )
33// Space complexity: O(n)
44
55/**
@@ -10,21 +10,29 @@ var groupAnagrams = function (strs) {
1010 const answer = [ ] ;
1111 const anagramDict = new Map ( ) ;
1212
13- const sortedStrs = strs . map ( ( str ) => {
14- const splitted = str . split ( "" ) ;
15- splitted . sort ( ) ;
16- return splitted . join ( "" ) ;
17- } ) ;
13+ const getKey = ( str ) => {
14+ const counter = Array . from (
15+ { length : "z" . charCodeAt ( ) - "a" . charCodeAt ( ) + 1 } ,
16+ ( ) => 0
17+ ) ;
1818
19- for ( let i = 0 ; i < sortedStrs . length ; i ++ ) {
20- const sortedStr = sortedStrs [ i ] ;
21- const originalStr = strs [ i ] ;
19+ for ( const chr of str ) {
20+ const index = chr . charCodeAt ( ) - "a" . charCodeAt ( ) ;
21+ counter [ index ] ++ ;
22+ }
23+
24+ return counter . join ( "#" ) ;
25+ } ;
26+
27+ for ( let i = 0 ; i < strs . length ; i ++ ) {
28+ const str = strs [ i ] ;
29+ const key = getKey ( str ) ;
2230
23- if ( ! anagramDict . has ( sortedStr ) ) {
24- anagramDict . set ( sortedStr , [ ] ) ;
31+ if ( ! anagramDict . has ( key ) ) {
32+ anagramDict . set ( key , [ ] ) ;
2533 }
2634
27- anagramDict . get ( sortedStr ) . push ( originalStr ) ;
35+ anagramDict . get ( key ) . push ( str ) ;
2836 }
2937
3038 for ( const [ _ , value ] of anagramDict ) {
0 commit comments