Minimum Insertion Steps to Make a String Palindrome
Minimum Insertion Steps to Make a String Palindrome is a hard dynamic programming problem solved with the strings pattern.
The best approach, n - lps (via lcs with the reverse), runs in O(n²) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from interval dp directly up.
Problem
Return the minimum number of characters to insert (anywhere) to make s a palindrome.
Examples
Example 1
- Input
s = "mbadm"- Output
2- Why
- mbdadbm or mdbabdm.
Example 2
- Input
s = "leetcode"- Output
5
Constraints
1 <= s.length <= 500; lowercase letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Interval DP directly | O(n²) | O(n²) |
| n - LPS (via LCS with the reverse) | O(n²) | O(n) |
1Interval DP directly
O(n²)O(n²)ins[i][j] = insertions to make s[i..j] a palindrome. Equal ends: ins[i + 1][j - 1]. Otherwise 1 + min(ins[i + 1][j], ins[i][j - 1]).
- Fill by increasing substring length.
class Solution {
public int minInsertions(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int len = 2; len <= n; len++)
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
dp[i][j] = s.charAt(i) == s.charAt(j)
? dp[i + 1][j - 1]
: 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
}
}class Solution:
def minInsertions(self, s: str) -> int:
n = len(s)
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = (dp[i + 1][j - 1] if s[i] == s[j]
else 1 + min(dp[i + 1][j], dp[i][j - 1]))
return dp[0][n - 1]class Solution {
public:
int minInsertions(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int len = 2; len <= n; len++)
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
dp[i][j] = s[i] == s[j]
? dp[i + 1][j - 1]
: 1 + min(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
}
};function minInsertions(s) {
const n = s.length;
const dp = Array.from({ length: n }, () => new Array(n).fill(0));
for (let len = 2; len <= n; len++)
for (let i = 0; i + len - 1 < n; i++) {
const j = i + len - 1;
dp[i][j] = s[i] === s[j]
? dp[i + 1][j - 1]
: 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
}2n - LPS (via LCS with the reverse)
O(n²)O(n)Keep the longest palindromic subsequence as the skeleton; every character outside it needs one matching insertion.
- lps = LCS(s, reverse(s)) with two rows.
- Return n - lps.
class Solution {
public int minInsertions(String s) {
String r = new StringBuilder(s).reverse().toString();
int n = s.length();
int[] prev = new int[n + 1], cur = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cur[j] = s.charAt(i - 1) == r.charAt(j - 1) ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
int[] t = prev; prev = cur; cur = t;
}
return n - prev[n];
}
}class Solution:
def minInsertions(self, s: str) -> int:
r = s[::-1]
n = len(s)
prev, cur = [0] * (n + 1), [0] * (n + 1)
for i in range(1, n + 1):
for j in range(1, n + 1):
cur[j] = prev[j - 1] + 1 if s[i - 1] == r[j - 1] else max(prev[j], cur[j - 1])
prev, cur = cur, prev
return n - prev[n]class Solution {
public:
int minInsertions(string s) {
string r(s.rbegin(), s.rend());
int n = s.size();
vector<int> prev(n + 1, 0), cur(n + 1, 0);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cur[j] = s[i - 1] == r[j - 1] ? prev[j - 1] + 1 : max(prev[j], cur[j - 1]);
swap(prev, cur);
}
return n - prev[n];
}
};function minInsertions(s) {
const r = s.split('').reverse().join('');
const n = s.length;
let prev = new Array(n + 1).fill(0), cur = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++)
cur[j] = s[i - 1] === r[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
[prev, cur] = [cur, prev];
}
return n - prev[n];
}Edge cases to test
- Already a palindrome (0)
Hints
Hint 1
Characters already in the longest palindromic subsequence need no partner. Every other character needs one inserted: answer = n - LPS(s).
FAQ
What is the best time complexity for Minimum Insertion Steps to Make a String Palindrome?
n - LPS (via LCS with the reverse) runs in O(n²) time and O(n) extra space.
Which pattern does Minimum Insertion Steps to Make a String Palindrome use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Common Subsequence, Longest Palindromic Subsequence.
Is there a brute force solution for Minimum Insertion Steps to Make a String Palindrome?
Yes. Interval DP directly takes O(n²) time and O(n²) space. ins[i][j] = insertions to make s[i..j] a palindrome.
Which edge cases should I test for Minimum Insertion Steps to Make a String Palindrome?
Already a palindrome (0).