Skip to content

LeetCode 1078: Occurrences After Bigram

A clear explanation of finding all words that follow a two-word sequence in a text string.

Problem Restatement

We are given a string text and two words first and second.

We need to return all words that come immediately after the bigram first second in text.

The official constraints state that 1 <= text.length <= 1000 and text consists only of lowercase English letters and spaces.

Input and Output

ItemMeaning
InputString text, words first and second
OutputList of words immediately following first second in the text

Function shape:

def findOcurrences(text: str, first: str, second: str) -> list[str]:
    ...

Examples

Example 1:

text = "alice is a good girl she is a good student"
first = "a"
second = "good"

"a good" appears before "girl" and "student".

Answer:

["girl", "student"]

Algorithm

Split the text and scan with a three-word sliding window.

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

Edge Cases

  • Check the minimum input size allowed by the constraints.
  • Verify duplicate values or tie cases if the input can contain them.
  • Keep the return value aligned with the exact failure case in the statement.

Complexity

MetricValueWhy
TimeO(n)Single pass through words
SpaceO(n)Split word list

Common Pitfalls

  • Do not optimize away the invariant; the code should still make it clear what condition is being maintained.
  • Prefer problem-specific names over one-letter variables once the logic becomes stateful.

Implementation

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> list[str]:
        words = text.split()
        return [words[i+2] for i in range(len(words) - 2)
                if words[i] == first and words[i+1] == second]

Testing

def run_tests():
    s = Solution()

    assert s.findOcurrences("alice is a good girl she is a good student", "a", "good") == ["girl", "student"]
    assert s.findOcurrences("we will we will rock you", "we", "will") == ["we", "rock"]
    assert s.findOcurrences("a b c a b", "a", "b") == ["c"]

    print("all tests passed")

run_tests()
TestExpectedWhy
Two occurrences["girl","student"]Bigram appears twice
Overlapping["we","rock"]Second match starts one position after first
Near end["c"]Last bigram has no following word