Minimum Insertion Steps to Make a String Palindrome Problem
Description
LeetCode Problem 1312.
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.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Constraints:
1 <= s.length <= 500sconsists of lowercase English letters.
Solution
Approach: Interval Dynamic Programming
Let f[i][j] be the fewest insertions that turn the substring s[i..j] into a palindrome. A single letter, or an empty range, is already a palindrome, so those are 0. For a longer range, look at its two ends:
- If
s[i] == s[j], they can be the outer pair of the palindrome, and only the inside needs fixing:f[i][j] = f[i + 1][j - 1]. - Otherwise one of them needs a partner. Either insert a copy of
s[j]befores[i]and fixs[i..j - 1], or insert a copy ofs[i]afters[j]and fixs[i + 1..j]:f[i][j] = 1 + min(f[i][j - 1], f[i + 1][j]).
f[i][j] depends on rows below and columns to the left, so fill i from the end of the string backwards and j forwards from i + 1. The answer is f[0][n - 1]. For "mbadm", the ends m match, and the inside "bad" needs two insertions ("bdadb"), giving 2.
Another way to see the answer: it is n minus the length of the longest palindromic subsequence, since every letter outside that subsequence needs exactly one inserted partner.
Complexity: O(n2) time and O(n2) space for a string of length n.
class Solution:
def minInsertions(self, s: str) -> int:
n = len(s)
# f[i][j]: the fewest insertions that make s[i..j] a palindrome (0 for one letter or an empty range).
f = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] # the two ends already match
else:
# Keep one end and insert a copy of it on the other side.
f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1
return f[0][n - 1]