Minimum Insertion Steps to Make a String Palindrome

Pattern: Strings DP

hard

Keep the longest palindromic subsequence; every other character needs a partner inserted. The answer is n - LPS(s).

The problem

Return the fewest characters you must insert anywhere in s to make it a palindrome. 'zzazz' gives 0; 'mbadm' gives 2.

Think first

  • Which characters can stay as they are?
  • What happens to the others?
  • Which earlier problem gives that?

Hints

    Brute force, and why it fails

    Try every insertion: exponential.

    The key insight

    The characters kept form a palindromic subsequence, so keeping the longest minimises insertions.

    Dry run

    lps5

    'zzazz' is already a palindrome: its LPS is 5.

    Step 1 of 2

    The plan

    return n - LPS(s)
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    One LPS table.

    Edge cases

    • Already a palindrome: 0.
    • All different: n - 1.
    • One character: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int minInsertions(String s) {
            int n = s.length();
            int[][] dp = new int[n][n];             // the longest palindromic subsequence of s[i..j]
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++)
                    dp[i][j] = s.charAt(i) == s.charAt(j) ? dp[i + 1][j - 1] + 2 : Math.max(dp[i + 1][j], dp[i][j - 1]);
            }
            return n - dp[0][n - 1];                // every character outside it needs a partner inserted
        }
    }

    C++

    class Solution {
    public:
        int minInsertions(string s) {
            int n = static_cast<int>(s.size());
            vector<vector<int>> dp(n, vector<int>(n, 0));   // the longest palindromic subsequence of s[i..j]
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++)
                    dp[i][j] = s[i] == s[j] ? dp[i + 1][j - 1] + 2 : max(dp[i + 1][j], dp[i][j - 1]);
            }
            return n - dp[0][n - 1];                // every character outside it needs a partner inserted
        }
    };

    Python

    class Solution:
        def minInsertions(self, s: str) -> int:
            n = len(s)
            dp = [[0] * n for _ in range(n)]        # the longest palindromic subsequence of s[i..j]
            for i in range(n - 1, -1, -1):
                dp[i][i] = 1
                for j in range(i + 1, n):
                    dp[i][j] = dp[i + 1][j - 1] + 2 if s[i] == s[j] else max(dp[i + 1][j], dp[i][j - 1])
            return n - dp[0][n - 1]                 # every character outside it needs a partner inserted

    Common mistakes

    • Counting deletions instead.
    • Using the longest palindromic substring.

    Similar problems