PS: This is not a duplicate of How to find the overlap between 2 sequences, and return it
[Although I ask for solutions in above approach if it could be applied to the following problem]
Q: Although I got it right, it is still not a scalable solution and is definitely not optimized (low on score). Read the following description of the problem and kindly offer better solution.
Question:
For simplicity, we require prefixes and suffixes to be non-empty and shorter than the whole string S. A border of a string S
is any string that is both a prefix and a suffix. For example, "cut"
is a border of a string "cutletcut"
, and a string "barbararhubarb"
has two borders: "b"
and "barb"
.
class Solution { public int solution(String S); }
that, given a string S
consisting of N
characters, returns the length of its longest border that has at least three non-overlapping occurrences in the given string. If there is no such border in S
, the function should return 0.
For example,
- if
S = "barbararhubarb"
the function should return1
, as explained above; - if
S = "ababab"
the function should return2
, as"ab"
and"abab"
are both borders ofS
, but only"ab"
has three non-overlapping occurrences; - if
S = "baaab"
the function should return0
, as its only border"b"
occurs only twice.
Assume that:
N
is an integer within the range[0..1,000,000]
;- string
S
consists only of lower-case letters (a−z
).
Complexity:
- expected worst-case time complexity is
O(N)
; - expected worst-case space complexity is
O(N)
(not counting the storage required for input arguments).
def solution(S):
S = S.lower()
presuf = []
f = l = str()
rank = []
wordlen = len(S)
for i, j in enumerate(S):
y = -i-1
f += S[i]
l = S[y] + l
if f==l and f != S:
#print f,l
new=S[i+1:-i-1]
mindex = new.find(f)
if mindex != -1:
mid = f #new[mindex]
#print mid
else:
mid = None
presuf.append((f,mid,l,(i,y)))
#print presuf
for i,j,k,o in presuf:
if o[0]<wordlen+o[-1]: #non overlapping
if i==j:
rank.append(len(i))
else:
rank.append(0)
if len(rank)==0:
return 0
else:
return max(rank)
My solutions time complexity is: O(N2) or O(N4) Help greatly appreciated.