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
+ /**
2
+ * @param {string[] } strList
3
+ * @return {string[][] }
4
+ */
5
+ var groupAnagrams = function ( strList ) {
6
+ const map = new Map ( ) ;
7
+
8
+ for ( const str of strList ) {
9
+ const sortedStr = str . split ( "" ) . sort ( ) . join ( "" ) ;
10
+
11
+ if ( ! map . has ( sortedStr ) ) {
12
+ map . set ( sortedStr , [ ] ) ;
13
+ }
14
+
15
+ map . get ( sortedStr ) . push ( str ) ;
16
+ }
17
+
18
+ return Array . from ( map . values ( ) ) ;
19
+ } ;
20
+
21
+ /**
22
+ * Time Complexity: O(n * k log k)
23
+ * Reason:
24
+ * - n is the number of strings in the input array.
25
+ * - k is the maximum length of a string in the input array.
26
+ * - Sorting each string takes O(k log k) time.
27
+ * - Thus, sorting all n strings takes O(n * k log k) time.
28
+ *
29
+ * Space Complexity: O(n * k)
30
+ * Reason:
31
+ * - We use a map to store the grouped anagrams.
32
+ * - In the worst case, we might store all n strings in the map.
33
+ * - Each string has a maximum length of k.
34
+ * - Thus, the space complexity is O(n * k).
35
+ */
You can’t perform that action at this time.
0 commit comments