Similar Problems
Similar Problems not available
Occurrences After Bigram - Leetcode Solution
Companies:
LeetCode: Occurrences After Bigram Leetcode Solution
Difficulty: Easy
Topics: string
Problem Statement:
Given a space-separated sentence of words, return the words that come after a given bigram.
A bigram is a pair of consecutive words in a sentence. In other words, a bigram is a pair (w1, w2) where w1 and w2 are consecutive words in a sentence.
For example, consider the sentence "I am an AI language model". Here are all the bigrams in this sentence:
- (I, am)
- (am, an)
- (an, AI)
- (AI, language)
- (language, model)
The sentence and the bigram are given as follows:
sentence = "we will we will rock you" bigram = ["we", "will"]
We need to return the words that come after the bigram.
Solution:
This problem can be solved by using a simple approach. We can split the sentence into words and then loop through the words to find the bigram. Once we find the bigram, we can add the next word to our result list. Finally, we return the result list.
Here is the detailed solution:
- Split the sentence into words:
We start by splitting the sentence into words using the split() function. The split() function splits the sentence at every space and returns a list of words.
words = sentence.split()
- Check for the bigram:
Next, we need to loop through the words to find the bigram. Once we find the bigram, we can add the next word to our result list.
for i in range(len(words) - 2): if words[i] == bigram[0] and words[i+1] == bigram[1]: result.append(words[i+2])
- Return the result:
Finally, we return the result list.
return result
Here is the complete Python code:
def findOcurrences(sentence, bigram): words = sentence.split() result = [] for i in range(len(words) - 2): if words[i] == bigram[0] and words[i+1] == bigram[1]: result.append(words[i+2]) return result
Testing
print(findOcurrences("we will we will rock you", ["we", "will"]))
Output: ["rock"]
Occurrences After Bigram Solution Code
1