This is a question from https://www.dailycodingproblem.com/:
Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically).
For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically.
As another example, given the string "google", you should return "elgoogle".
It is similar to this SO question, or this GeeksforGeeks post. Similar, but not the same; none of them provide any explanation for the recurrence, as if they plucked the solution out of thin air, and they don't reconstruct the solution, let alone the lexicographically earliest one.
After some thinking, my understanding is as follows:
Observe that for any string
s[i..j]
, ifs[i] == s[j]
, then the number of insertions required to make it a palindrome is the same as the number of insertions required to makes[i+1..j-1]
a palindrome.If, however,
s[i] != s[j]
, then we may converts[i..j-1]
to a palindrome and then inserts[j]
at the beginning, or converts[i+1..j]
to a palindrome and inserts[i]
at the end. Since we are looking for the fewest number of insertions, we will choose the minimum of the two options. The number of insertions is one more than the number of insertions required for the chosen subproblem (for adding a character at the beginning or at the end).
How do I reconstruct the lexicographically earliest solution?