Minimum Insertion Steps to Make a String Palindrome — LeetCode 1312 Python Solution

HardStringDynamic Programming
Problem
#1312
Reading time
2 min

The problem

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

Example

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

Python solution

Python
class Solution:
    def minInsertions(self, s: str) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= j:
                return 0
            if s[i] == s[j]:
                return dfs(i + 1, j - 1)
            return 1 + min(dfs(i + 1, j), dfs(i, j - 1))

        return dfs(0, len(s) - 1)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome?
LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome is rated Hard on LeetCode.
What topics does LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome cover?
LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview