LeetCode 1078. Occurrences After Bigram

Description

https://leetcode.com/problems/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"]

Note:

  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.

Explanation

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 = text.split()
        
        i = 0
        
        while i < len(text) - 2:
            
            if text[i] == first and text[i + 1] == second:
                results.append(text[i + 2])
                
            i += 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 *