![]() |
VOOZH | about |
Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.
Examples:
Input: s = "geeks"
Output: 3
Explanation: "skgeegks" is a palindromic string, which requires 3 insertions.Input: s= "abcd"
Output: 3
Explanation: "abcdcba" is a palindromic string.Input: s= "aba"
Output: 0
Explanation: Given string is already a palindrome hence no insertions are required.
Table of Content
Let minimum number of insertions in the string str[lā¦..h] be findMinInsertions(str[lā¦..h]). It can be recursively defined as.
- if str[l] is equal to str[h], then findMinInsertions(str[l+1ā¦..h-1])
- Else min(findMinInsertions(str[lā¦..h-1]), findMinInsertions(str[l+1ā¦..h])) + 1
3
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: The minimum number of insertions required to make the substring str[l...h] a palindrome depends on the optimal solutions of its subproblems. If str[l] is equal to str[h] then we call recursive call on l + 1 and h - 1 other we make two recursive call to get optimal answer.
2. Overlapping Subproblems: When using a recursive approach, we notice that certain subproblems are computed multiple times. To avoid this redundancy, we can use memoization by storing the results of already computed subproblems in a 2D array.
The problem involves changing two parameters: l (starting index) and h (ending index). Hence, we need to create a 2D array of size (n x n) to store the results, where n is the length of the string. By using this 2D array, we can efficiently reuse previously computed results and optimize the solution.
3
The iterative approach for finding the minimum number of insertions needed to make a string palindrome follows a similar concept to the recursive solution but builds the solution in a bottom-up manner using a 2D dynamic programming table.
Base Case:
- if l == h than dp[l][h] = 0. Where 0 <= l <= n - 1
- If the substring has two characters (h == l + 1), we check if they are the same. If they are, dp[l][h] = 0, otherwise, dp[l][h] = 1.
Recursive Case:
- If str[l] == str[h], then dp[l][h] = dp[l+1][h-1].
- Otherwise, dp[l][h] = min(dp[l+1][h], dp[l][h-1]) + 1.
3
The idea is to reuse the array in such a way that we store the results for the previous row in the same array while iterating through the columns.
3
Related article: