Please note that in the palindrome all pairs of characters with equal distance to the middle of the line are equal.
This suggests the following algorithm:
Find the largest palindrome suffix, then add the back of the substring to the left of this palindrome suffix. This will give you the shortest palindrome you can get by adding characters to the end of the line.
A rough implementation of this would be O(n^2) . You can get O(n) with two rolling hashes to check if the suffix is ββa palindrome in O(1) .
It describes how these hashes work:
hForward(suff) = suff[0] * p^0 + suff[1] * p^1 + ... + suff[k] * p^k hBackward(suff) = suff[k] * p^0 + suff[k-1] * p^1 + ... + suff[0] * p^k When adding a new character to the suffix: Note that this is added to the beginning, since we should iterate the suffixes from right to left. hForward(c + suff) = c * p^0 + p * hForward(suff) hBackward(c + suff) = hBackward(suff) + c * p^(k + 1)
Where p should probably be (small-ish) simple, and you should do all the calculations for another (large-ish) simple. To maintain efficiency, calculate the power gradually, do not use the exponential algorithm. You can use more hashes to avoid false positives.
If I donβt mess things up, there is also a solution that includes the KMP algorithm, but I am no longer familiar with it.
Ivlad
source share