Problem Description
Given a string s
. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s
palindrome. A Palindrome String is one that reads the same backward as well as forward.
Key Insights
- To make a string palindrome, we can insert characters to match corresponding characters from both ends.
- The problem can be solved using dynamic programming by finding the longest palindromic subsequence.
- The minimum insertions required will be equal to the length of the string minus the length of the longest palindromic subsequence.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n)
Solution
The approach to solve this problem involves using dynamic programming to calculate the length of the longest palindromic subsequence (LPS) in the string. The idea is to fill a 2D table where each entry dp[i][j]
represents the length of the longest palindromic subsequence in the substring s[i...j]
.
- If the characters at the ends of the current substring are the same (
s[i] == s[j]
), then they are part of the LPS and we increment the count from the inner substrings[i+1...j-1]
. - If they are not the same, we take the maximum length by either ignoring the left character or the right character.
- The base case is that single-character substrings are palindromes of length 1.
After filling the table, the minimum insertions required will be the total length of the string minus the length of the LPS.