Minimum Insertion Steps to Make a String Palindrome — LeetCode 1312 Python Solution
HardStringDynamic Programming
- Problem
- #1312
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.