LeetCode 1078. Occurrences After Bigram



Given words first and second, consider occurrences in some text of the form “first second third“, where second comes immediately after first, and third comes immediately after second.

For each such occurrence, add “third” to the answer, and return the answer.

Example 1:

Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]

Example 2:

Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]


  1. 1 <= text.length <= 1000
  2. text consists of space separated words, where each word consists of lowercase English letters.
  3. 1 <= first.length, second.length <= 10
  4. first and second consist of lowercase English letters.


We can convert text to a list of words and search the “second” string in the list. If we find the “second” string in the list, we can check if the previous word in the list is the “first” string, if it is, we add the next word after the “second” string. Keep searching, until no more text words.

Python Solution

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        results = []
        text_words = text.split()
        while second in text_words:
            second_index = text_words.index(second)
            if second_index > 0 and second_index < len(text_words) - 1 and text_words[second_index - 1] == first:
                results.append(text_words[second_index + 1])
            text_words = text_words[second_index + 1:]
        return results
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *