0

I am trying to create a suffix array using python language.My program is not passing all of the test cases and shows timeout error. I think its time complexity is O(NlogNlogN). here is my code :

def criteria1(s):
    return s[0]


def criteria2(s):
    return s[1]


def criteria3(s):
    return s[0][0]


text='banana'
l=len(text)
s=[]            
for i in range(l): 
    s.append([[ord(text[i])-ord('a'),None],i]) # s is list of [[rank1,rank2],original_index] where rank1 is set according to first character of suffices of 'text'

doTill=1
while doTill<l:
    for i in range(l): # assigning the second rank
        try:
            s[i][0][1]=s[i+doTill][0][0]
        except IndexError:
            s[i][0][1]=-1

    s.sort(key=criteria1)  # sorting based on [rank1,rank2]
    #print('first sort',s)
    temp=list(s[0][0])     # now assigning new rank1 based on [rank1,rank2]
    s[0][0][0]=0           # setting rank1 of first element to 0
    r=0
    for i in range(1,l):
        if temp==s[i][0]:
            s[i][0][0]=r
        else:
            temp=list(s[i][0])
            r+=1
            s[i][0][0]=r
    #print('reassign ranks',s)
    s.sort(key=criteria2)    # again sorting based on original_index of suffices
    doTill*=2
s.sort(key=criteria3)        # now getting the required suffix array from s by first sorting it according to rank1 and then getting original_indices
for i in range(l):
    s[i]=s[i][1]
print(s)

Please provide suggestions to improve my code and its time complexity. Thanks in advance

Mr Sukhe
  • 67
  • 9
  • Can you explain what exactly the code is supposed to do? – tobias_k Mar 12 '20 at 10:46
  • @tobias_k it is used to generate suffix array for a given text. in this case the text is 'banana'. the suffix array is printed in the last line. further i use the suffix array to calculate number of occurance of a sub string in the given string. for example 'na' accurs 2 times and 'a' occurs 3 times in 'banana'. the numbr of occurance is required for some reason – Mr Sukhe Mar 12 '20 at 11:01

0 Answers0