Skip to main content
Back to problems
#1455
Easy Algorithms

Check if a word occurs as a prefix of any word in a sentence

Two Pointers String String Matching
68.8% acceptance
Feb 25, 2026
1325
59
Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence. Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 {
    for (i, word) in sentence.split_whitespace().enumerate() {
      if word.starts_with(&search_word as &str) {
        return (i + 1) as i32;
      }
    }
    -1
  }
}