I am trying to solve this HackerRank challenge which asks to write a function that prints the indexes of all sentences which contain the query words. For example, if the inputs to the function are:
textQueries(sentences, queries)
textQueries(['jim likes mary','kate likes tom', 'tom does not like jim'],['jim tom', 'likes'])
Then the function will print
2
0 1
If there is no sentence contains the query words, -1
will be printed
The constraints for the inputs are:
- The length of the
sentences
andqueries
lists will not exceed 10000. - The number of words in any sentence or query is from 1 to 10 words.
- Each word has at most 11 characters.
- No word appears in more than 10 sentences.
- Each word consists of uppercase and lowercase English letters only.
My attempt so far is to create a hashmap which maps each single query word with a set that contains the indexes to the sentences which contain that word, then I intersect those sets with each other to get the final set. My code runs fine, but it is slow for large test cases. Is there any way I can have it optimized?
def textQueries(sentences, queries):
word_map = {}
for query in queries:
query_words = query.split()
final_set = set([])
set_modified = False
for query_word in query_words:
if query_word in word_map:
if len(final_set) == 0 and not set_modified:
final_set = word_map[query_word]
set_modified = True
continue
elif len(final_set) == 0 and set_modified:
break
else:
final_set = final_set.intersection(word_map[query_word])
continue
else:
sentences_contain_word = []
for index, sentence in enumerate(sentences):
words = sentence.split()
if query_word in words:
sentences_contain_word.append(index)
if len(sentences_contain_word) >= 10:
break
word_map[query_word] = set(sentences_contain_word)
if len(final_set) == 0 and not set_modified:
final_set = word_map[query_word]
set_modified = True
elif len(final_set) == 0 and set_modified:
break
else:
final_set = final_set.intersection(word_map[query_word])
if len(final_set) == 0:
print(-1)
else:
for index in sorted(final_set):
print(str(index), end=' ')
print()
2
followed by0 1
if I execute the code. Could you verify that your code and the example output are correct? \$\endgroup\$2
and0 1
sorry for the confusion \$\endgroup\$