We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I have solved this question in O(n3) complexity
but i am getting TLE in some test cases.
How can i decrease the time complexity, any ideas?
#!/bin/python3importosimportsys## Complete the playWithWords function below.#deflcs(a,b,n):m=nlcs=[[0foriinrange(m+1)]forjinrange(n+1)]foriinrange(1,n+1):forjinrange(1,m+1):ifa[i-1]==b[j-1]:lcs[i][j]=lcs[i-1][j-1]+1else:lcs[i][j]=max(lcs[i-1][j],lcs[i][j-1])returnlcs[n][m]defplayWithWords(s):ans=0dic={}forwinrange(0,len(s)-2):s1=s[:w+1]l1=len(s1)revs1=s1[l1::-1]#print('s1',s1)#print('revs1',revs1)s2=s[w+1:]l2=len(s2)revs2=s2[l2::-1]#print(s2)#print(lcs(s1,revs1,l1))#print(lcs(s2,revs2,l2))ifs1indic:lcs1=dic[s1]else:dic[s1]=lcs(s1,revs1,l1)lcs1=dic[s1]ifs2indic:lcs2=dic[s2]else:dic[s2]=lcs(s2,revs2,l2)lcs2=dic[s2]temp=lcs1*lcs2iftemp>ans:ans=tempreturnansif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')s=input()result=playWithWords(s)fptr.write(str(result)+'\n')fptr.close()
I am getting TLE error
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Play with words
You are viewing a single comment's thread. Return to all comments →
I have solved this question in O(n3) complexity but i am getting TLE in some test cases. How can i decrease the time complexity, any ideas?
I am getting TLE error