Skip to content

Commit 57396b6

Browse files
committed
Runtime: 194 ms (Top 50.00%) | Memory: 46.5 MB (Top 62.50%)
1 parent 4c15bd3 commit 57396b6

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

scripts/algorithms/F/Find the Shortest Superstring/Find the Shortest Superstring.js

+11-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
// Runtime: 194 ms (Top 50.00%) | Memory: 46.5 MB (Top 62.50%)
12
var shortestSuperstring = function(words) {
23
let N = words.length, suffixes = new Map(),
34
edges = Array.from({length: N}, () => new Uint8Array(N))
4-
5+
56
// Build the edge graph
67
for (let i = 0, word = words; i < N; i++) {
78
let word = words[i]
@@ -20,11 +21,11 @@ var shortestSuperstring = function(words) {
2021
edges[i][j] = Math.max(edges[i][j], k)
2122
}
2223
}
23-
24+
2425
// Initialize DP array
25-
let M = N - 1,
26+
let M = N - 1,
2627
dp = Array.from({length: M}, () => new Uint16Array(1 << M))
27-
28+
2829
// Helper function to find the best value for dp[curr][currSet]
2930
// Store the previous node with bit manipulation for backtracking
3031
const solve = (curr, currSet) => {
@@ -38,16 +39,16 @@ var shortestSuperstring = function(words) {
3839
}
3940
return (bestOverlap << 4) + bestPrev
4041
}
41-
42+
4243
// Build DP using solve
4344
for (let currSet = 1; currSet < 1 << M; currSet++)
4445
for (let curr = 0; curr < N; curr++)
45-
if (currSet & 1 << curr)
46+
if (currSet & 1 << curr)
4647
dp[curr][currSet] = solve(curr, currSet)
47-
48+
4849
// Join the ends at index M
4950
let curr = solve(M, (1 << N) - 1) & (1 << 4) - 1
50-
51+
5152
// Build the circle by backtracking path info from dp
5253
// and find the best place to cut the circle
5354
let path = [curr], currSet = (1 << M) - 1,
@@ -59,7 +60,7 @@ var shortestSuperstring = function(words) {
5960
lowOverlap = overlap, bestStart = N - path.length
6061
curr = prev, path.unshift(curr)
6162
}
62-
63+
6364
// Build and return ans by cutting the circle at bestStart
6465
let ans = []
6566
for (let i = bestStart; i < bestStart + M; i++) {
@@ -68,4 +69,4 @@ var shortestSuperstring = function(words) {
6869
}
6970
ans.push(words[path[(bestStart+M)%N]])
7071
return ans.join("")
71-
};
72+
};

0 commit comments

Comments
 (0)