LeetCode #1312 Hard

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.
  • s has at most 500 letters, so an O(n²) table of about 250,000 cells is fast enough.
Constraints
  • 1 <= s.length <= 500
  • s consists of lowercase English letters.
dpstringlcs
Open on LeetCode ↗
02

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] after s[j] (then solve s[i+1..j]), or a copy of s[j] before s[i] (then solve s[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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

6

Return the top-right cell

dp[0][n-1] covers the whole string, so it is the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minInsertions(self, s: str) -> int:
▶3 n = len(s)
▶4 dp = [[0] * n for _ in range(n)]
▶5 for i in range(n - 2, -1, -1):
▶6 for j in range(i + 1, n):
▶7 if s[i] == s[j]:
▶8 dp[i][j] = dp[i + 1][j - 1]
▶9 else:
▶10 dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j - 1])
▶11 return dp[0][n - 1]
mbadmmbadm00000single letters cost 0, 10 cells to fill
n5
Cell (i, j) will hold the fewest insertions that make the substring from i to j a palindrome. One letter on its own already reads the same both ways, so the diagonal is 0.
mbadmijmbadm000010d≠m0drop d0drop m1 +0=1d and m differ → one insertion + cheaper side 0 = 1
i3
j4
dp1
'd' and 'm' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'd' leaves the part from 4 to 4 (cost 0); mirroring 'm' leaves 3 to 3 (cost 0). Both cost the same, so this cell is 1 + 0 = 1.
mbadmijmbadm0001010a≠d0drop a0drop d1 +0=1a and d differ → one insertion + cheaper side 0 = 1
i2
j3
dp1
'a' and 'd' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'a' leaves the part from 3 to 3 (cost 0); mirroring 'd' leaves 2 to 2 (cost 0). Both cost the same, so this cell is 1 + 0 = 1.
mbadmijmbadm00012010a≠m1drop a1drop m1 +1=2a and m differ → one insertion + cheaper side 1 = 2
i2
j4
dp2
'a' and 'm' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'a' leaves the part from 3 to 4 (cost 1); mirroring 'm' leaves 2 to 3 (cost 1). Both cost the same, so this cell is 1 + 1 = 2.
mbadmijmbadm001012010b≠a0drop b0drop a1 +0=1b and a differ → one insertion + cheaper side 0 = 1
i1
j2
dp1
'b' and 'a' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'b' leaves the part from 2 to 2 (cost 0); mirroring 'a' leaves 1 to 1 (cost 0). Both cost the same, so this cell is 1 + 0 = 1.
mbadmijmbadm0012012010b≠d1drop b1drop d1 +1=2b and d differ → one insertion + cheaper side 1 = 2
i1
j3
dp2
'b' and 'd' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'b' leaves the part from 2 to 3 (cost 1); mirroring 'd' leaves 1 to 2 (cost 1). Both cost the same, so this cell is 1 + 1 = 2.
mbadmijmbadm00123012010b≠m2drop b2drop m1 +2=3b and m differ → one insertion + cheaper side 2 = 3
i1
j4
dp3
'b' and 'm' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'b' leaves the part from 2 to 4 (cost 2); mirroring 'm' leaves 1 to 3 (cost 2). Both cost the same, so this cell is 1 + 2 = 3.
mbadmijmbadm010123012010m≠b0drop m0drop b1 +0=1m and b differ → one insertion + cheaper side 0 = 1
i0
j1
dp1
'm' and 'b' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'm' leaves the part from 1 to 1 (cost 0); mirroring 'b' leaves 0 to 0 (cost 0). Both cost the same, so this cell is 1 + 0 = 1.
mbadmijmbadm0120123012010m≠a1drop m1drop a1 +1=2m and a differ → one insertion + cheaper side 1 = 2
i0
j2
dp2
'm' and 'a' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'm' leaves the part from 1 to 2 (cost 1); mirroring 'a' leaves 0 to 1 (cost 1). Both cost the same, so this cell is 1 + 1 = 2.
mbadmijmbadm01230123012010m≠d2drop m2drop d1 +2=3m and d differ → one insertion + cheaper side 2 = 3
i0
j3
dp3
'm' and 'd' cannot be the outer pair, so one of them gets a copy inserted on the far side. Mirroring 'm' leaves the part from 1 to 3 (cost 2); mirroring 'd' leaves 0 to 2 (cost 2). Both cost the same, so this cell is 1 + 2 = 3.
mbadmijmbadm012320123012010m=m2inside→2ends m and m match → cost of the inside, 2
i0
j4
dp2
Both ends are 'm', so they can be the outer pair of the palindrome as they are. Only the inside, from 1 to 3, needs work, and that cell already says 2.
mbadmmbadm012320123012010answer: 2 insertions
return2
The top-right cell covers the whole string, from 0 to 4. Every shorter substring was settled before it, so 2 is the fewest insertions for all of 'mbadm'.
mbadabmmbadm012320123012010insert a and b → mbadabm
palindromembadabm
Walking back from the top-right cell shows which letters to add. Matching ends are kept; at a mismatch, follow the cheaper cell and write the dropped letter on both sides. The highlighted letters are the 2 inserted ones, and 'mbadabm' reads the same both ways.
05

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.

▶1class Solution:
▶2 def minInsertions(self, s: str) -> int:
▶3 n = len(s)
▶4 r = s[::-1]
▶5 prev = [0] * (n + 1)
▶6 for i in range(1, n + 1):
▶7 cur = [0] * (n + 1)
▶8 for j in range(1, n + 1):
▶9 if s[i - 1] == r[j - 1]:
▶10 cur[j] = prev[j - 1] + 1
▶11 else:
▶12 cur[j] = max(prev[j], cur[j - 1])
▶13 prev = cur
▶14 return n - prev[n]
06

Common pitfalls

Filling rows from the top

✗ Wrong
for i in range(n):
    for j in range(i + 1, n):
✓ Right
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

✗ Wrong
i, j = 0, n - 1
while i < j:
    if s[i] != s[j]: steps += 1
    i += 1; j -= 1
✓ Right
dp[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.

07

Edge cases

Already a palindrome, like "zzazz"

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.

All letters different, like "abc"

No pair ever matches, each length adds one, and the answer is n - 1: mirror every letter except one middle letter.

08

Complexity

Time
O(n²)
Space
O(n²)
There are about n²/2 cells above the diagonal and each takes O(1) work. The table can be cut to one row of length n (keep the old dp[i+1][j-1] in a variable), which gives O(n) space.
09

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.