Occurrences After Bigram - Problem
You're given two strings first and second, and a text string containing multiple words. Your task is to find all occurrences of the pattern "first second third" in the text, where:
secondcomes immediately afterfirstthirdcomes immediately aftersecond
Return an array of all the third words that complete this pattern.
Example: If first = "we", second = "will", and text = "we will rock you we will go there", you should return ["rock", "go"] because both "we will rock" and "we will go" match the pattern.
Input & Output
example_1.py โ Basic Pattern Matching
$
Input:
text = "we will rock you we will go there", first = "we", second = "will"
โบ
Output:
["rock", "go"]
๐ก Note:
Found two occurrences of 'we will': 'we will rock' and 'we will go'. The third words are 'rock' and 'go'.
example_2.py โ Single Match
$
Input:
text = "alice is a good girl she is a good student", first = "a", second = "good"
โบ
Output:
["girl", "student"]
๐ก Note:
Found two patterns 'a good': 'a good girl' and 'a good student'. Return both third words.
example_3.py โ No Matches
$
Input:
text = "hello world how are you", first = "we", second = "will"
โบ
Output:
[]
๐ก Note:
The pattern 'we will' does not exist in the text, so return empty array.
Constraints
- 1 โค text.length โค 1000
- text consists of lowercase English letters and spaces
- All words in text are separated by single space
- 1 โค first.length, second.length โค 10
- first and second consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Setup Window
Create a sliding window that tracks the last 2 words seen
2
Scan Text
Move through each word, checking if the window contains our target pattern
3
Pattern Match
When the pattern matches, record the current word as a result
4
Update Window
Shift the window forward by updating the tracked words
Key Takeaway
๐ฏ Key Insight: By maintaining a sliding window of the last 2 words, we can detect patterns in O(n) time with O(1) space, making this much more efficient than checking every possible position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code