AlgoViz

Minimum insertions to make string palindrome

Hard

Keep the longest palindromic core

Problem

Return the fewest characters to insert to make a string a palindrome.

In simple words

Insertions needed = length minus the longest palindromic subsequence already inside.

The idea

The characters already forming the longest palindromic subsequence can stay; everything else needs a matching insertion. So the answer is n minus that subsequence's length.

The trick

  • Answer = n - longestPalindromicSubsequence(s).
  • Which itself is n - LCS(s, reverse(s)).
·
A
C
0
0
0
A
0
0
0
B
0
0
0
C
0
0
0

Step 1 of 8. LCS grid for "ABC" and "AC". Match → diagonal + 1, else the best of up/left.

1/8
Optimal
timeO(n·m)spaceO(n·m)

Match extends the diagonal.

1for (let i = 1; i <= n; i++)2  for (let j = 1; j <= m; j++)3    dp[i][j] = a[i-1] === b[j-1]4      ? dp[i-1][j-1] + 15      : Math.max(dp[i-1][j], dp[i][j-1]);

Input

grid
5 × 4

Memory

at
cells marked
0

Output

LCS

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
s = "abcaa"
Output:
2
Explanation:
Add 2 letters to mirror it.

Example 2

Input:
s = "aa"
Output:
0
Explanation:
Already a palindrome → 0.

Example 3

Input:
s = "abc"
Output:
2
Explanation:
Need 2 insertions.

Finished the walkthrough? Add it to your streak.