Skip to main content
Back to problems
#1078
Easy Algorithms

Occurrences after bigram

String
63.9% acceptance
Feb 25, 2026
528
371
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".

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_ocurrences(text: String, first: String, second: String) -> Vec<String> {
    let words: Vec<&str> = text.split_whitespace().collect();
    let mut res = vec![];
    for i in 0..words.len().saturating_sub(2) {
      if words[i] == first && words[i+1] == second {
        res.push(words[i+2].to_string());
      }
    }
    res
  }
}