This approach utilizes dynamic programming to find the longest palindromic subsequence in the given string. The minimum number of insertions required is the difference between the length of the string and this subsequence. The idea is to consider characters from both ends of the string and make decisions accordingly using a DP table.
Time Complexity: O(n^2), where 'n' is the length of the string. This is due to the nested loops filling the DP table.
Space Complexity: O(n^2), as it uses a two-dimensional array for the DP table.
1function minInsertions(s) {
2 const n = s.length;
3 const dp = Array.from({ length: n }, () => Array(n).fill(0));
4 for (let len = 1; len < n; len++) {
5 for (let i = 0, j = len; j < n; i++, j++) {
6 if (s[i] === s[j]) {
7 dp[i][j] = dp[i + 1][j - 1];
8 } else {
9 dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
10 }
11 }
12 }
13 return dp[0][n - 1];
14}
15
16console.log(minInsertions("mbadm"));
The JavaScript implementation uses a 2D array filled with zeros initially. We iterate over substring lengths, setting dp values based on comparisons of boundary characters.
This approach leverages a recursive function to explore all possibilities, but uses memoization to cache results of previously computed subproblems. This reduces redundant calculations.
Time Complexity: O(n^2)
Space Complexity: O(n^2) due to the memoization table.
1using System;
2
3public class RecurMemo {
4 int[,] dp;
5
6 private int Solve(string s, int left, int right) {
7 if (left >= right) return 0;
8 if (dp[left, right] != -1) return dp[left, right];
9 if (s[left] == s[right])
10 dp[left, right] = Solve(s, left + 1, right - 1);
11 else
12 dp[left, right] = 1 + Math.Min(Solve(s, left + 1, right), Solve(s, left, right - 1));
13 return dp[left, right];
14 }
15
16 public int MinInsertions(string s) {
17 int n = s.Length;
18 dp = new int[n, n];
19 for (int i = 0; i < n; i++)
20 for (int j = 0; j < n; j++)
21 dp[i, j] = -1;
22 return Solve(s, 0, n - 1);
23 }
24
25 public static void Main(string[] args) {
26 RecurMemo recurMemo = new RecurMemo();
27 Console.WriteLine(recurMemo.MinInsertions("mbadm"));
28 }
29}
A C# solution featuring recursive computation with memoization. The dp
matrix is utilized to store results of overlapping subproblems.