Skip to content

1312. Minimum Insertion Steps to Make a String Palindrome

Difficulty Topics

Description

Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

Palindrome String is one that reads the same backward as well as forward.

 

Example 1:

Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.

Example 2:

Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".

Example 3:

Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Solution

minimum-insertion-steps-to-make-a-string-palindrome.py
class Solution:
    def lps(self, start, end, s, mem):
        if start == end: return 1
        if start > end: return 0
        if mem[start][end]: return mem[start][end]

        mem[start][end] = 2 + self.lps(start+1, end-1, s, mem) if s[start] == s[end] else max(self.lps(start, end-1, s, mem), self.lps(start+1, end, s, mem))

        return mem[start][end]

    def minInsertions(self, s: str) -> int:
        n = len(s)
        mem = [[0]*n for _ in range(n)]    

        return n - self.lps(0, n-1, s, mem)