1312. Minimum Insertion Steps to Make a String Palindrome
Problem
Return the minimum number of characters to insert anywhere in s to make it a palindrome.
Example: "zzazz" → 0; "mbadm" → 2 (e.g. "mbdadbm")
Constraints: length ≤ 500.
Characters already forming the longest palindromic subsequence stay; every other character needs a mirror insert: n − LPS(s).
Complexity: O(n²).
class Solution:
def minInsertions(self, s: str) -> int:
n = len(s)
dp = [0] * n
for l in range(n - 1, -1, -1):
dp[l], diag = 1, 0
for r in range(l + 1, n):
tmp = dp[r]
dp[r] = diag + 2 if s[l] == s[r] else max(dp[r], dp[r - 1])
diag = tmp
return n - dp[n - 1]
assert Solution().minInsertions("zzazz") == 0
assert Solution().minInsertions("mbadm") == 2
assert Solution().minInsertions("leetcode") == 5
class Solution {
public int minInsertions(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int l = n - 1; l >= 0; l--) {
dp[l][l] = 1;
for (int r = l + 1; r < n; r++)
dp[l][r] = s.charAt(l) == s.charAt(r) ? dp[l + 1][r - 1] + 2 : Math.max(dp[l + 1][r], dp[l][r - 1]);
}
return n - dp[0][n - 1];
}
}
func minInsertions(s string) int {
n := len(s)
dp := make([]int, n) // longest palindromic subsequence, one row at a time
for l := n - 1; l >= 0; l-- {
dp[l] = 1
diag := 0
for r := l + 1; r < n; r++ {
tmp := dp[r]
if s[l] == s[r] {
dp[r] = diag + 2
} else {
dp[r] = max(dp[r], dp[r-1])
}
diag = tmp
}
}
return n - dp[n-1] // every character outside it needs a mirror
}