File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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)
You can’t perform that action at this time.
0 commit comments