A palindrome string is one that reads the same backward as well as forward.
You are given a string 'str'.
Find the minimum number of characters needed to insert in 'str' to make it a palindromic string.
Input: 'str' = "abca"
Output: 1
Explanation:
If we insert the character ‘b’ after ‘c’, we get the string "abcba", which is a palindromic string. Please note that there are also other ways possible.
The first line contains a string 'str', containing lowercase English letters i.e from ‘a’ to ‘z’.
The output contains a single integer denoting the minimum number of insertions needed to make 'str' palindrome.
You do not need to print anything; it has already been taken care of. Just implement the given function.
abca
1
If we insert the character ‘b’ after ‘c’, we get the string "abcba", which is a palindromic string. Please note that there are also other ways possible.
abcdefg
6
aaaaa
0
The expected time complexity is O(|str| ^ 2).
1 <= |str| <= 1000
Where |str| represents the length of the string 'str'.
Time Limit: 1 sec.
The very first approach can be to try all possible substrings of the string and minimize the ans among the valid ones.
Let’s understand with an example:
Consider the string 'str' = “abcca” .
O(2 ^ n), where 'n' is the length of the string.
In the worst case, at every step, we are making 2 recursive calls. Hence, the overall complexity is O(2 ^ n).
O(n), where 'n' is the length of the string.
In the worst case, extra space is used by the recursion stack which goes to a maximum depth of 'n'.