For finding the position of a substring, inside a string, a naive algorithm will take O(n^2)
time. However, using some efficient algorithms (eg KMP algorithm), this can be achieved in O(n) time:
s = 'saurabh'
w = 'au'
def get_table():
i = 0; j = 2
t = []
t.append(-1); t.append(0)
while i < len(w):
if w[i] == w[j-1]:
t.append(j+1)
j += 1
else:
t.append(0)
j = 0
i += 1
return t
def get_word():
t = get_table()
i = j = 0
while i+j < len(s):
if w[j] == s[i+j]:
if j == len(w) - 1:
return i
j += 1
else:
if t[j] > -1:
i = i + j - t[j]
j = t[j]
else:
i += 1
return -1
if __name__ == '__main__':
print get_word()
However, if we do: 'saurabh'.index('ra')
, does it internally uses some efficient algorithm to compute this in O(n)
or it uses naive algorithm of complexity O(n^2)
?
Sometimes you can get a quick answer just by trying