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:

  • second comes immediately after first
  • third comes immediately after second

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
Sliding Window Pattern MatchingText: "we will rock you we will go there"Target: first="we", second="will"Step 1: Initialize sliding windowSliding Window[prev2] [prev1] [current]wewillrockStep 2: Pattern match detected!"we will" โœ“โ†’ Collect "rock"rockStep 3: Continue sliding...willrockyouNo match: "will rock" โ‰  "we will"Step 4: Another match found!"we will" โœ“โ†’ Collect "go"goFinal Result: ["rock", "go"]
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.
Asked in
Google 15 Amazon 8 Microsoft 6 Meta 4
28.4K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen