DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Minimum Insertion Steps to Make a String Palindrome

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 don't 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:

class Solution:
    def minIns(self, s, i, j):
        if i == j:
            return 0
        if i == j - 1:
            if s[i] == s[j]:
                return 0
            return 1
        if (i, j) in self.cache:
            return self.cache[(i, j)]
        if s[i] == s[j]:
            curr = self.minIns(s, i + 1, j - 1)
            self.cache[(i, j)] = curr
            return curr
        else:
            curr = 1 + min(self.minIns(s, i + 1, j), self.minIns(s, i, j - 1))
            self.cache[(i, j)] = curr
            return curr

    def minInsertions(self, s: str) -> int:
        self.cache = {}
        return self.minIns(s, 0, len(s) - 1)
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay