PS: This is not a duplicate. How to find the overlap between 2 sequences and return it
[Although I ask for solutions in the above approach, if it can be applied to the next problem]
Q: Although I understood correctly, it is still not a scalable solution and is definitely not optimized (low score). Read the following description of the problem and suggest the best solution.
Question:
For simplicity, we require that the prefixes and suffixes be non-empty and shorter than the whole string S. The boundary of the string S is any string that is both a prefix and a suffix. For example, "cut" is the boundary of the string "cutletcut" , and the string "barbararhubarb" has two boundaries: "b" and "barb" .
class Solution { public int solution(String S); }
which, given the string S , consisting of characters N , returns the length of the longest border, which contains at least three non-overlapping occurrences in the given string. If there is no such boundary in S , the function should return 0.
For instance,
- if
S = "barbararhubarb" function should return 1 , as described above; - if
S = "ababab" function should return 2 , since "ab" and "abab" are both boundaries of S , but only "ab" has three non-overlapping occurrences; - if
S = "baaab" function should return 0 , since its only border "b" occurs only twice.
Let's pretend that:
N is an integer in the range [0..1,000,000] ;- string
S consists only of lowercase letters ( aβz ).
Complexity:
- expected worst-case time complexity
O(N) ; - the expected worst case complexity is
O(N) (not counting the storage needed for the 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 time complexity of solutions: O (N 2) or O (N 4) Help with gratitude.