File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ // n: length of strs, m: length of strs[i]
2+ // Time complexity: O(nmlogm)
3+ // Space complexity: O(n)
4+
5+ /**
6+ * @param {string[] } strs
7+ * @return {string[][] }
8+ */
9+ var groupAnagrams = function ( strs ) {
10+ const answer = [ ] ;
11+ const anagramDict = new Map ( ) ;
12+
13+ const sortedStrs = strs . map ( ( str ) => {
14+ const splitted = str . split ( "" ) ;
15+ splitted . sort ( ) ;
16+ return splitted . join ( "" ) ;
17+ } ) ;
18+
19+ for ( let i = 0 ; i < sortedStrs . length ; i ++ ) {
20+ const sortedStr = sortedStrs [ i ] ;
21+ const originalStr = strs [ i ] ;
22+
23+ if ( ! anagramDict . has ( sortedStr ) ) {
24+ anagramDict . set ( sortedStr , [ ] ) ;
25+ }
26+
27+ anagramDict . get ( sortedStr ) . push ( originalStr ) ;
28+ }
29+
30+ for ( const [ _ , value ] of anagramDict ) {
31+ answer . push ( value ) ;
32+ }
33+
34+ return answer ;
35+ } ;
You can’t perform that action at this time.
0 commit comments