Minimum Insertion Steps to Make a String Palindrome (LeetCode 1312): Solution and Explanation

Hard
Dynamic Programming
String

Find the fewest characters you must insert anywhere in s to turn it into a palindrome. Interval DP over substrings answers it in O(n^2).

Intuition

A palindrome pairs its first letter with its last. Look at the two ends of s: if they are equal, they can stay a pair, and the problem shrinks to the inside.

If they differ, one of them has no partner. The cheapest fix is to insert a copy of it on the other side. That costs one step and removes that letter from the problem, so you try both ends and keep the cheaper one.

Every substring s[i..j] has the same structure, so dp[i][j] can be filled from shorter substrings, one length at a time, starting from single letters which need nothing.

Approach: Interval DP by substring length

  1. Create an n x n table dp of zeros. Single letters (dp[i][i]) and empty ranges need 0 insertions.
  2. For length from 2 to n, for every start i, let j = i + length - 1.
  3. If s[i] == s[j], set dp[i][j] = dp[i + 1][j - 1].
  4. Otherwise set dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j - 1]).
  5. Return dp[0][n - 1].

Step-by-step example

s = "mbadm"
  1. Length 2: "mb", "ba", "ad", "dm" all have different ends, so each needs 1.
  2. Length 3: "bad" has ends b and d, so it is 1 + min(dp["ad"], dp["ba"]) = 2. "mba" and "adm" are also 2.
  3. Length 4: "mbad" and "badm" are 1 + 2 = 3.
  4. Length 5: "mbadm" starts and ends with m, so it equals dp["bad"] = 2.
  5. The answer is 2, for example "mbdadbm".

Code: Python, Java, C++

1class Solution:
2    def minInsertions(self, s: str) -> int:
3        n = len(s)
4        dp = [[0] * n for _ in range(n)]
5        for length in range(2, n + 1):
6            for i in range(n - length + 1):
7                j = i + length - 1
8                if s[i] == s[j]:
9                    dp[i][j] = dp[i + 1][j - 1]
10                else:
11                    dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j - 1])
12        return dp[0][n - 1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are about n^2 / 2 substrings and each cell is filled in O(1) from cells already computed.

Space

O(n^2)

The full table is stored. Since each diagonal only reads the previous two, it can be cut to O(n) with a 1D array.

Other approaches

n minus the longest palindromic subsequence (time O(n^2), space O(n))

Letters in the longest palindromic subsequence already mirror each other, and every other letter needs one inserted partner. Compute the LPS as the LCS of s and reverse(s) and return n - LPS.

Top-down memoization (time O(n^2), space O(n^2))

Recurse on (i, j) with the same two cases and cache results. Easy to write, but recursion depth can reach n.

Common mistakes

  • Filling the table row by row from the top. dp[i][j] needs dp[i + 1][...], so fill by increasing length (or loop i from n - 1 down to 0).
  • Reading dp[i + 1][j - 1] when j - i = 1. That cell lies below the diagonal; it must be 0, which a zero-initialised table gives you.
  • Adding 1 when the ends match. Equal ends cost nothing; only a mismatch costs an insertion.
  • Trying to count insertions greedily from the outside in. A locally cheap choice can block a much longer matching subsequence later.

Frequently asked questions

Why is the answer n minus the longest palindromic subsequence?

The letters of the longest palindromic subsequence can be kept as the skeleton of the palindrome. Each remaining letter needs exactly one inserted copy on the opposite side, and you can never do better because a smaller count would imply a longer palindromic subsequence.

Does inserting at the left end versus the right end matter?

Not for the count. The two options dp[i + 1][j] and dp[i][j - 1] correspond to mirroring s[i] or mirroring s[j], and the recurrence keeps whichever is cheaper.

Can I also build the palindrome?

Yes. Walk back from dp[0][n - 1]: on a match keep both ends, on a mismatch follow the smaller neighbour and insert a copy of the end you dropped on the other side.