Occurrences After Bigram — LeetCode 1078 Python Solution
- Problem
- #1078
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.