Problem Description
Given a string s, you can insert any character at any index. The goal is to determine the minimum number of insertions required to make s a palindrome. A palindrome is a string that reads the same forwards and backwards.
Key Insights
- The problem can be re-framed in terms of finding the Longest Palindromic Subsequence (LPS) in the given string.
- The minimum number of insertions required is equal to the length of the string minus the length of the LPS.
- Dynamic Programming (DP) is used to compute the LPS efficiently by solving overlapping subproblems.
- A bottom-up DP approach iterating over smaller substrings and expanding them is effective.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Solution
We use dynamic programming to compute the longest palindromic subsequence (LPS) of the given string. We initialize a 2D dp array where dp[i][j] stores the length of the LPS in the substring s[i...j].
- If s[i] equals s[j], then dp[i][j] is 2 plus dp[i+1][j-1] (or 1 if i equals j).
- If they do not match, dp[i][j] takes the maximum value from dp[i+1][j] or dp[i][j-1].
After filling the dp table for the entire string, the minimum insertions required is the difference between the string's length and the LPS length (i.e., len(s) - dp[0][n-1]).
This approach efficiently fills out the DP table in a bottom-up manner.