Occurrences After Bigram - 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".

Input & Output

Example 1 — Basic Pattern Matching
$ Input: text = "alice is a girl she is a student", first = "a", second = "girl"
Output: ["she"]
💡 Note: The pattern "a girl" appears once in the text, followed by "she", so we return ["she"]
Example 2 — Multiple Occurrences
$ Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]
💡 Note: Pattern "we will" appears twice: first followed by "we", second followed by "rock"
Example 3 — No Matches
$ Input: text = "alice is a girl", first = "bob", second = "is"
Output: []
💡 Note: The pattern "bob is" never appears 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 a single space
  • 1 ≤ first.length, second.length ≤ 10
  • first and second consist of lowercase English letters

Visualization

Tap to expand
Occurrences After Bigram INPUT Text String: alice is a girl she is a student [0] [1] [2] [3] [4] [5] [6] [7] Input Values: first = "a" second = "girl" Looking for pattern: "a" "girl" [third] = "first" match ALGORITHM STEPS 1 Split text Split into words array 2 Scan words Loop i from 0 to n-2 3 Check bigram If words[i]=first AND words[i+1]=second 4 Collect third Add words[i+2] to result Single Pass Scan at i=2: a i girl i+1 she i+2 Match found! Add "she" (i=6: "a student" - no match) FINAL RESULT Output Array: ["she"] Why "she"? Pattern "a girl [third]" found at position 2-3-4 third word = "she" Status: OK 1 occurrence found Key Insight: Use single pass scan with sliding window of 3 consecutive words. Check if words[i] matches "first" and words[i+1] matches "second". If both match, collect words[i+2] as the "third" word. Time: O(n), Space: O(n) where n is number of words in text. TutorialsPoint - Occurrences After Bigram | Single Pass Scan Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
285 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