I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ?
For example,
Input: S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox Q: lazy brown dog
Output: [11,15]
My code:
S = raw_input().strip().split(' ')
Q = raw_input().strip().split(' ')
count = [0 for x in range(len(Q))]
smallest_index = [0 for x in range(len(Q))]
largest_index = [0 for x in range(len(Q))]
for i in range(len(S)):
for j in range(len(Q)):
if S[i] == Q[j]:
count[j] += 1
if count[j] <= 1:
smallest_index[j] = i
largest_index[j] = i
if count[j] > 1:
largest_index[j] = i
largest_index.sort()
print "[%d," % largest_index[0],
print "%d]" % largest_index[len(Q)-1]
smallest_index
values but never using them? But apart from that I don't think that your algorithm will always find the correct minimal solution. The minimal range could be one that uses the largest indices, the smallest indices, or somewhere in the middle. – PM 2Ring