Given two strings first and second, consider occurrences in some text of the form “first second third”, where first and second are exactly the words first and second, respectively, and third is the word immediately following them.
Return a list of all the words third for each instance of “first second third” in the text.
Example:
text = "alice is a good girl she is a good student"
first = "a"
second = "good"
should return ["girl", "student"].
text, first, and second are lowercase and without punctuation.first and second appear at the end of the text without a subsequent third word?
first second, skip this occurrence.first second third is a distinct occurrence, and the search should continue after this occurrence.text into a list of words.first second.first second is found and a subsequent word exists, add the subsequent word to the result list.def findOcurrences(text, first, second):
words = text.split()
result = []
for i in range(len(words) - 2):
if words[i] == first and words[i + 1] == second:
result.append(words[i + 2])
return result
# Example usage
text = "alice is a good girl she is a good student"
first = "a"
second = "good"
print(findOcurrences(text, first, second)) # Output: ["girl", "student"]
n is the number of characters in the text.m is the number of words in the list.Thus, the overall time complexity is O(n + m), which is essentially linear with respect to the length of the input text and the number of words in the list. Since m will usually be much smaller than n, the complexity can often be considered O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?