Skip to content

Commit ffd7243

Browse files
Create Min_palindrome.js
1 parent 1f560a0 commit ffd7243

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: Strings/Min_palindrome.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function minInsertionStepsToPalindrome(str) {
2+
const n = str.length;
3+
// Create a 2D array to store the minimum steps needed to make substrings palindrome
4+
const dp = Array.from({ length: n }, () => Array(n).fill(0));
5+
6+
// Base case: single characters are palindromes, so dp[i][i] = 0
7+
for (let i = 0; i < n; i++) {
8+
dp[i][i] = 0;
9+
}
10+
11+
// Fill the dp table in bottom-up manner
12+
for (let len = 2; len <= n; len++) {
13+
for (let i = 0; i < n - len + 1; i++) {
14+
const j = i + len - 1;
15+
if (str[i] === str[j]) {
16+
// If the characters at the ends are the same, no additional insertion is needed
17+
dp[i][j] = dp[i + 1][j - 1];
18+
} else {
19+
// Otherwise, choose the minimum between inserting character at i or j
20+
dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
21+
}
22+
}
23+
}
24+
25+
return dp[0][n - 1];
26+
}
27+
28+
// Example usage:
29+
const str = "abcd";
30+
const minInsertions = minInsertionStepsToPalindrome(str);
31+
console.log("Minimum insertion steps:", minInsertions); // Output: 3 (abcd -> dabcbad)

0 commit comments

Comments
 (0)