Occurrences After Bigram — LeetCode 1078 Python Solution

EasyString
Problem
#1078
Pattern
Hash Map
Reading time
2 min

The problem

Given two strings 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. Return an array of all the words third for each occurrence of "first second third".

Example

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

Python solution

Python
class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        words = text.split()
        ans = []
        for i in range(len(words) - 2):
            a, b, c = words[i : i + 3]
            if a == first and b == second:
                ans.append(c)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1078. Occurrences After Bigram is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1078. Occurrences After Bigram?
LeetCode 1078. Occurrences After Bigram is rated Easy on LeetCode.
What topics does LeetCode 1078. Occurrences After Bigram cover?
LeetCode 1078. Occurrences After Bigram is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview