Given a string, figure out how many characters minimum are needed to make the word a palindrome. Examples:
ABBA : 0 (already a palindrome) ABB: 1 FAE: 2 FOO: 1
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.
Algorithms only, since this is probably homework [Apologies to Raymond, it’s an interview question rather than homework, as his edits/comments make clear. However, the algorithms and added pseudo-code are still valid for that purpose, and I’ve added some C code at the end].
You need to find the longest palindrome at the end of the string. An algorithm to see if a string is a palindrome can be created by simply running one pointer from the start of the string and one from the end, checking that the characters they refer to are identical, until they meet in the middle. Something like:
Try that with the full string. If that doesn’t work, save the first character on a stack then see if the remaining characters form a palindrome. If that doesn’t work, save the second character as well and check again from the third character onwards.
Eventually you’ll end up with a series of saved characters and the remaining string which is a palindrome.
Best case is if the original string was a palindrome in which case the stack will be empty. Worst case is one character left (a one-character string is automatically a palindrome) and all the others on the stack.
The number of characters you need to add to the end of the original string is the number of characters on the stack.
To actually make the palindrome, pop the characters off the stack one-by-one and put them at the start and the end of the palindromic string.
Examples:
Converting this method to “code”:
For those less interested in pseudo-code, here’s a test program in C which does the trick.
Running this with:
gives the output: