0

The problem I am trying to solve:

Given a string, split the string into two substrings at every possible point. The rightmost substring is a suffix. The beginning of the string is the prefix. Determine the lengths of the common prefix between each prefix and the original string. Sum and return the lengths of the common prefixes. Return an array where each element 'i' is the sum for the string 'i'.

My Solution:

def commonPrefix(l):

    size=len(l)  #Finding number of strings
    sumlist=[]  #Initializing list that'll store sums
    for i in range(size):
        total=0  #Initializing total common prefixes for every string
        string=l[i]  #Storing each string in string
        strsize=len(string)  #Finding length of each string
        for j in range(strsize):
            suff=string[j:]   #Calculating every suffix for a string
            suffsize=len(suff)  #Finding length of each suffix
            common=0   #Size of common prefix for each length
            for k in range(suffsize):
                if(string[k]==suff[k]):
                    common=common+1
                else:
                    break   #If characters at equal positions are not equal, break
            total=total+common   #Update total for every suffix
        sumlist.append(total)   #Add each total in list
    return sumlist   #Return list

My Solution takes up a lot of time, I need help with optimizing it.

  • 2
    This is a question for [codereview](http://codereview.stackexchange.com/) – Cid Nov 23 '20 at 13:48
  • What does *"Determine the lengths of the common prefix between each prefix and the original string"* mean? Simply determine the length of this prefix? Sounds vaguely like you are trying to discover suffix trees. – tripleee Nov 23 '20 at 14:05
  • @tripleee example: https://ibb.co/jV1LgM7 – Rohit Sharma Nov 23 '20 at 14:08
  • Yup, looks like a suffix tree alright. See e.g. https://stackoverflow.com/questions/9452701/ukkonens-suffix-tree-algorithm-in-plain-english – tripleee Nov 23 '20 at 14:11
  • Try profiling your code so you can work out what is slow. [This](https://github.com/pyutils/line_profiler) profiler gives you line-by-line data. – 8n8 Nov 23 '20 at 14:27
  • This question is basically asking you to compute the Z array (from the Z algorithm https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/) and sum its entries. Computing the Z array can be done in linear time. – Kurt Tomlinson Feb 28 '21 at 16:07

0 Answers0