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.
1def minInsertions(s):
2 n = len(s)
3 dp = [[0] * n for _ in range(n)]
4 for length in range(1, n):
5 for i in range(n - length):
6 j = i + length
7 if s[i] == s[j]:
8 dp[i][j] = dp[i + 1][j - 1]
9 else:
10 dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j - 1])
11 return dp[0][n - 1]
12
13print(minInsertions("mbadm"))
In Python, we create a list of lists as our DP table. For each substring length, we determine the least insertions needed by comparing characters from both ends, adjusting counts based on matches or not.
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.
1#include <iostream>
2#include <vector>
3#include <string>
4using namespace std;
5
6vector<vector<int>> dp;
7
8int solve(const string &s, int left, int right) {
9 if (left >= right) return 0;
10 if (dp[left][right] != -1) return dp[left][right];
11 if (s[left] == s[right])
12 dp[left][right] = solve(s, left + 1, right - 1);
13 else
14 dp[left][right] = 1 + min(solve(s, left + 1, right), solve(s, left, right - 1));
15 return dp[left][right];
16}
17
18int minInsertions(string s) {
19 int n = s.length();
20 dp.resize(n, vector<int>(n, -1));
21 return solve(s, 0, n - 1);
22}
23
24int main() {
25 cout << minInsertions("mbadm") << endl;
26 return 0;
27}
In C++, a recursive function solve
is utilized. Memoization is achieved using a 2D vector to store intermediate results, reducing redundant recursive calls.