You are given a string s. In one step you can insert any character at any position of the string.
Return the minimum number of steps needed to make s a palindrome. A palindrome is a string that reads the same backward as forward.
Function Signature
def min_insertions(s: str) -> int:
Rules
-
Insertion is the only allowed operation. The original characters of
s
cannot be deleted, replaced or reordered.
-
Return only the count of insertions, not the resulting palindrome.
Constraints
-
1 <= len(s) <= 500
-
s
contains only lowercase English letters.
Examples
Input: s = "zzazz"
Output: 0
"zzazz" already reads the same in both directions, so no insertions are needed.
Input: s = "mbadm"
Output: 2
Two insertions can produce "mbdadbm" or "mdbabdm", and both contain "mbadm" with its letters in their original order. No single insertion turns "mbadm" into a palindrome.
Input: s = "leetcode"
Output: 5
Inserting d, o, c, e and l gives "leedoctcodeel", which is a palindrome. Four insertions are not enough, because "e" is the only letter that appears more than once, so most of the original letters have no equal letter to pair with.