The "Occurrences After Bigram" problem asks you to analyze a string of words and find all words that immediately follow a specific pair of consecutive words (a bigram).
Given:
text
containing words separated by spaces.first
and second
.text
where the word first
is immediately followed by second
, and collect the word that comes right after this pair (if any).
text = "we will we will rock you", first = "we", second = "will"
["we", "rock"]
because "we will we" and "we will rock" are the two occurrences.
To solve this problem, let's first break down what we need:
first
and second
, grab the following word.
Let's walk through the steps to solve this problem efficiently:
text
into an array (or list) of words.
i
, check if words[i]
is equal to first
and words[i+1]
is equal to second
.words[i+2]
to the result list (since it's the word that follows the bigram).
Let's use the input:
text = "alice is a good girl she is a good student"
first = "a"
, second = "good"
Step-by-step:
["alice", "is", "a", "good", "girl", "she", "is", "a", "good", "student"]
["girl", "student"]
Brute-force approach:
text
. We loop through the list once.The "Occurrences After Bigram" problem is a great example of a simple sliding window approach. By splitting the input into words and scanning with a window of size three, we can efficiently find all words that follow a given bigram. The solution is elegant because it makes a single pass, uses minimal space, and is easy to reason about, making it suitable even for large input sizes.
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> list:
words = text.split()
res = []
for i in range(len(words) - 2):
if words[i] == first and words[i+1] == second:
res.append(words[i+2])
return res
class Solution {
public:
vector<string> findOcurrences(string text, string first, string second) {
vector<string> words, res;
istringstream iss(text);
string word;
while (iss >> word) {
words.push_back(word);
}
for (int i = 0; i + 2 < words.size(); ++i) {
if (words[i] == first && words[i+1] == second) {
res.push_back(words[i+2]);
}
}
return res;
}
};
class Solution {
public String[] findOcurrences(String text, String first, String second) {
String[] words = text.split(" ");
List<String> result = new ArrayList<>();
for (int i = 0; i + 2 < words.length; i++) {
if (words[i].equals(first) && words[i+1].equals(second)) {
result.add(words[i+2]);
}
}
return result.toArray(new String[0]);
}
}
var findOcurrences = function(text, first, second) {
const words = text.split(' ');
const res = [];
for (let i = 0; i < words.length - 2; i++) {
if (words[i] === first && words[i+1] === second) {
res.push(words[i+2]);
}
}
return res;
};