Input:
There is a long String S
and we have a array of integers A
which denotes the prefixes of the String S
like A[i]
denotes the prefix S[0..A[i]]
Output:
Return an array Output[]
of the same size as A
where Output[i]
is the length of the longest matching suffix of S[0..A[i]]
and S
Sample Input:
S = "ababa"
A[]=[0, 1, 2, 3, 4]
Sample Output:
Output[]=[1,0,3,0,5]
The most naive algorithm which I have is for every A[i]
just match the number of characters between S[0..A[i]]
and S
from the end of both strings. But this algorithm is O(n^2)
where n is the length of the original String S.
Question:
Is there is a better algorithm which pre processes the string S and then can quickly return the longest length suffix for the entire input Array?