I have given word like abca. I want to know how many letters do I need to add to make it palindrome.
In this case its 1, because if I add b, I get abcba.
I have given word like abca . I want to know how many letters
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, let’s consider an inefficient recursive solution:
Suppose the string is of the form
aSb, whereaandbare letters andSis a substring.If
a==b, thenf(aSb) = f(S).If
a!=b, then you need to add a letter: either add anaat the end, or add abin the front. We need to try both and see which is better. So in this case,f(aSb) = 1 + min(f(aS), f(Sb)).This can be implemented with a recursive function which will take exponential time to run.
To improve performance, note that this function will only be called with substrings of the original string. There are only O(n^2) such substrings. So by memoizing the results of this function, we reduce the time taken to O(n^2), at the cost of O(n^2) space.