This is the Substring Game! challenge from HackerEarth:
Watson gives Sherlock a string (let's denote it by S). Watson calculates all the substrings of S in his favourite order.
According to the Watson's favourite order, all the substrings starting from first character of the string will occur first in the sorted order of their length, followed by all the substrings starting from the second character of the string in the sorted order of their length, and so on.
For example, suppose S = abc. Then, all the substrings of S as per Watson's favourite order are:
Watson will ask Sherlock 'q' questions. In each question, Watson will give Sherlock a number and Sherlock has to speak the substring on that number. If there is no possible substring, then Sherlock has to speak -1.
Can the below code be improved to run in \$o(n^2)\$ complexity?
str=raw_input() q=int(raw_input()) num=raw_input().split(' ') substr= for i,s in enumerate(str): #print i,s for j in range(i+1,len(str)+1): #print j substr.append(s+str[i+1:j]) #print substr for i in range(0,q): try: print substr[int(num[i])-1] except IndexError: print -1
First line is the string - abc
Second line is the number of substrings asked- 2
Third line is the position of the substrings to return from the list of substrings- 2 5
The list of substrings would be ['a','ab','abc','b','bc','c']