1
+ // Runtime: 194 ms (Top 50.00%) | Memory: 46.5 MB (Top 62.50%)
1
2
var shortestSuperstring = function ( words ) {
2
3
let N = words . length , suffixes = new Map ( ) ,
3
4
edges = Array . from ( { length : N } , ( ) => new Uint8Array ( N ) )
4
-
5
+
5
6
// Build the edge graph
6
7
for ( let i = 0 , word = words ; i < N ; i ++ ) {
7
8
let word = words [ i ]
@@ -20,11 +21,11 @@ var shortestSuperstring = function(words) {
20
21
edges [ i ] [ j ] = Math . max ( edges [ i ] [ j ] , k )
21
22
}
22
23
}
23
-
24
+
24
25
// Initialize DP array
25
- let M = N - 1 ,
26
+ let M = N - 1 ,
26
27
dp = Array . from ( { length : M } , ( ) => new Uint16Array ( 1 << M ) )
27
-
28
+
28
29
// Helper function to find the best value for dp[curr][currSet]
29
30
// Store the previous node with bit manipulation for backtracking
30
31
const solve = ( curr , currSet ) => {
@@ -38,16 +39,16 @@ var shortestSuperstring = function(words) {
38
39
}
39
40
return ( bestOverlap << 4 ) + bestPrev
40
41
}
41
-
42
+
42
43
// Build DP using solve
43
44
for ( let currSet = 1 ; currSet < 1 << M ; currSet ++ )
44
45
for ( let curr = 0 ; curr < N ; curr ++ )
45
- if ( currSet & 1 << curr )
46
+ if ( currSet & 1 << curr )
46
47
dp [ curr ] [ currSet ] = solve ( curr , currSet )
47
-
48
+
48
49
// Join the ends at index M
49
50
let curr = solve ( M , ( 1 << N ) - 1 ) & ( 1 << 4 ) - 1
50
-
51
+
51
52
// Build the circle by backtracking path info from dp
52
53
// and find the best place to cut the circle
53
54
let path = [ curr ] , currSet = ( 1 << M ) - 1 ,
@@ -59,7 +60,7 @@ var shortestSuperstring = function(words) {
59
60
lowOverlap = overlap , bestStart = N - path . length
60
61
curr = prev , path . unshift ( curr )
61
62
}
62
-
63
+
63
64
// Build and return ans by cutting the circle at bestStart
64
65
let ans = [ ]
65
66
for ( let i = bestStart ; i < bestStart + M ; i ++ ) {
@@ -68,4 +69,4 @@ var shortestSuperstring = function(words) {
68
69
}
69
70
ans . push ( words [ path [ ( bestStart + M ) % N ] ] )
70
71
return ans . join ( "" )
71
- } ;
72
+ } ;
0 commit comments