Minimum Insertion Steps to Make a String Palindrome
Minimum Insertion Steps to Make a String Palindrome is LeetCode 1312 (Hard). In one step you may insert any character at any position of s. Return the minimum insertions to make the string a palindrome.
- Nothing can be deleted or replaced, only inserted.
shas at most 500 letters, so an O(n²) table of about 250,000 cells is fast enough.
- 1 <= s.length <= 500
- s consists of lowercase English letters.
Intuition
Look only at the two ends of a substring s[i..j]. In the finished palindrome, its first and last letters must be equal.
- Ends already match: keep both. They mirror each other, so the cost is whatever the inside
s[i+1..j-1]needs. - Ends differ: one of them needs a new partner on the other side. Insert a copy of
s[i]afters[j](then solves[i+1..j]), or a copy ofs[j]befores[i](then solves[i..j-1]). Pay 1 and take the cheaper side.
Every substring depends only on shorter ones, so fill the table from short substrings to long ones and read the answer for the whole string.
"Fewest edits to make a string a palindrome" on a string of a few hundred letters points to a DP over substrings [i, j]. Longest Palindromic Subsequence and Palindrome Partitioning II fill the same kind of table.
Approach
Before reading on, decide what the first and last letters of s must turn into in the final palindrome. Write the cost of s[i..j] in terms of shorter substrings, then pick a fill order so every value you need already exists. Aim for O(n²) time.
Two ways to count the insertions
dp[i][j] is the cost of s[i..j], built from the two end letters.
- Direct: the table holds insertions, so no conversion at the end.
- Recovers the palindrome: walking the table back shows which letters to insert.
Find the longest palindromic subsequence as the longest common subsequence of s and its reverse, then subtract it from n.
- Reuses LCS: handy if that table is already familiar.
- Two rows: only the previous row is kept, so memory is O(n).
Both run in O(n²) time. The substring table is traced below; the subsequence version follows the demo.
Set up the table
Make an n × n table dp of zeros, where dp[i][j] will be the fewest insertions that make s[i..j] a palindrome. A single letter is already a palindrome, so the diagonal stays 0, and an empty range below the diagonal also counts as 0.
Fill rows from the bottom up
Loop i from n - 2 down to 0 and j from i + 1 up to n - 1. The cells a value needs are dp[i+1][...] (the row below) and dp[i][j-1] (the cell to the left), and this order fills both before they are read.
Matching ends cost nothing
If s[i] == s[j], set dp[i][j] = dp[i+1][j-1]. The two equal letters can sit at the two ends of the palindrome as they are, so only the inside needs work. For two equal neighbours the inside is empty and the cost is 0.
Different ends cost one insertion
Otherwise set dp[i][j] = 1 + min(dp[i+1][j], dp[i][j-1]). One of the two end letters gets a copy inserted on the far side, which settles that letter; trying both sides and keeping the smaller covers every possible palindrome.
Why matching ends can always be kept
Suppose some best answer does not pair s[i] with s[j] even though they are equal. Its outer letters are then insertions, and swapping them for the two original letters never costs more. So pairing equal ends is never worse, and the match case does not need to try the other options.
Return the top-right cell
dp[0][n-1] covers the whole string, so it is the answer.
Code in Python, C++ and Java
Length minus longest palindromic subsequence
Letters that already form a palindrome in order can stay; every other letter needs one inserted partner. The longest such set is the longest common subsequence of s and its reverse, so the answer is n minus its length.
Common pitfalls
Filling rows from the top
for i in range(n):
for j in range(i + 1, n):for i in range(n - 2, -1, -1):
for j in range(i + 1, n):dp[i][j] reads row i + 1, which a top-down loop has not filled yet, so it sees zeros. For "abc" the cell for the whole string reads dp[1][2] = 0 and returns 1 instead of 2.
Counting mismatched pairs from the outside in
i, j = 0, n - 1
while i < j:
if s[i] != s[j]: steps += 1
i += 1; j -= 1dp[i][j] = 1 + min(dp[i+1][j], dp[i][j-1])
An insertion shifts one side by a letter, so after it the pairs no longer line up at fixed positions. For "leetcode" it gives 4 while the true answer is 5, and for "abcb" it gives 2 while 1 insertion ("abcba") is enough.
Edge cases
Every outer pair matches and copies its inner cell, so the zeros carry all the way to dp[0][n-1] and the answer is 0.
No pair ever matches, each length adds one, and the answer is n - 1: mirror every letter except one middle letter.
Complexity
n (keep the old dp[i+1][j-1] in a variable), which gives O(n) space.Minimum Insertion Steps to Make a String Palindrome FAQ
How do I get the actual palindrome, not just the count?
Start at i = 0, j = n - 1. If the ends match, put that letter on both sides and move inward. If not, follow the smaller of dp[i+1][j] and dp[i][j-1]: the letter you drop is written on both sides. For "mbadm" this builds "mbdadbm" or "mbadabm", both with 2 insertions.
Is the answer the same as the minimum deletions to make a palindrome?
Yes. Deleting a letter and inserting a copy of it on the other side fix the same unmatched letter, so both counts equal n minus the longest palindromic subsequence. The same table solves the deletion version.
What if insertions are only allowed at the front?
That is Shortest Palindrome (problem 214). With only one side open, the answer depends on the longest palindromic prefix, which KMP or Z-function finds in O(n). This table would overcount there because it assumes both sides are open.