1312. Minimum Insertion Steps to Make a String Palindrome
Problem 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.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
1 | Input: s = "zzazz" |
Example 2:
1 | Input: s = "mbadm" |
Example 3:
1 | Input: s = "leetcode" |
Solution:
Let’s imagine matching the characters of the string like a palindrome, from the begining and the end with 2 pointers i
and j
.We may encounter 2 scenarios:
- The character at
i
matches character atj
. - The characters don’t match each other
In case of 1 we just increase the pointer i
and decrease the pointer j
, i++
and j--
respectively.
In the second case we have 2 options:
- Insert one character at
j
to match the character ati
.
Or
- Insert one character at
i
to match the character atj
.
Since we are not actually adding the characters in the string but just calculating the cost,In case 1 we increase the pointer i
by 1
and j
stays as it is, as we still need a character to match at j
and in case 2 we decrease the pointer j
by 1
and i
stays as it is, as we still need a character to match at i
.both the cases adds cost 1
since we are inserting a letter.
We can then use these two different pairs of new i
and j
values (i+1, j
and i, j-1
) to again repeat the process and use the minimum result of these as our result for current pair of i, j
.We can see that this is recursive and thus we can use recursion with caching to store the repeated values.
1 | class Solution: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: