According to this wikipedia article, for each row S of length n at time O (n), we can compute an array A of the same size as:
A [i] == 1 if the prefix S of length i is a palindrome.
http://en.wikipedia.org/wiki/Longest_palindromic_substring
The algorithm should be found in:
Manacher, Glenn (1975), "New linear" on-line "algorithm for finding the smallest initial string palindrome"
In other words, we can check which line prefixes are palindromes in linear time. We will use this result to solve the proposed problem.
Each (non-rotating) palindrome S has the following form: S = psxs ^ Rp ^ R.
Where "x" is the center of the palindrome (empty string or single letter), "p" and "s" are (possibly empty) strings, and "s ^ R" means "s" string reverse.
Each rotating palindrome created from this line has one of the following two forms (for some p):
- sxs ^ Rp ^ Rp
- p ^ Rpsxs ^ R
This is true because you can choose whether to cut a substring before or after the middle of the palindrome, and then paste it on the other end.
As can be seen, the substrings "p ^ Rp" and "sxs ^ R" are palindromes, one of which is of even length, and the other is of odd length if S is of odd length.
We can use the algorithm mentioned in the wikipedia link to create two arrays A and B. Array A is created by checking which prefixes are palindromes and B for suffixes. Then we look for the value i such that A [i] == B [i] == 1 such that either the prefix or suffix has an even length. We will find such an index if the proposed line is a rotary palindrome, and the even part is a substring "p ^ Rp", so we can easily restore the original palindrome by moving half of this line to the other end of the line.
One remark on the solution using rks, this solution does not work, because for line S = 1121 it will create line 11211121, which has a palindrome longer than or equal to length S, but is not a rotary palindrome. If we change the solution so that it checks if a palindrome of length equal to length S exists, this will work, but I donβt see a direct solution how to change the search algorithm for the longest substring so that it will look for a substring of a fixed length (len ( S)). (I did not write this as a comment in the solution, since I am new to Stackoverflow and do not have a sufficient reputation for this)
Second remark - I am sorry that I did not include the Manacher algorithm, if someone has a link to the idea of ββthe algorithm or some implementation, please include it in the comments.