Check If a Word Occurs As a Prefix of Any Word in a Sentence
Problem
You are given a sentence made of space-separated lowercase words and a target searchWord. Scan the words from left to right and return the 1-based index of the first word that begins with searchWord (that is, searchWord is a prefix of that word). If no word starts with searchWord, return −1.
sentence = "i love eating burger", searchWord = "burg"4def is_prefix_of_word(sentence, search_word):
words = sentence.split()
for i, word in enumerate(words):
if word.startswith(search_word):
return i + 1
return -1
function isPrefixOfWord(sentence, searchWord) {
const words = sentence.split(" ");
for (let i = 0; i < words.length; i++) {
if (words[i].startsWith(searchWord)) return i + 1;
}
return -1;
}
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].startsWith(searchWord)) return i + 1;
}
return -1;
}
}
int isPrefixOfWord(string sentence, string searchWord) {
istringstream ss(sentence);
string word;
int i = 1;
while (ss >> word) {
if (word.rfind(searchWord, 0) == 0) return i;
i++;
}
return -1;
}
Explanation
The sentence is just a list of words joined by single spaces, so the first move is to split it into individual words. After splitting "i love eating burger" we get the list ["i", "love", "eating", "burger"].
Now we walk through the words from left to right and, for each one, ask a single yes/no question: does this word start with searchWord? A built-in like startsWith (or str.startswith in Python) compares the leading characters of the word against searchWord and tells us instantly.
The problem wants the position of the first matching word, counting from 1. So the moment we find a word that begins with searchWord, we return its 1-based index and stop — we do not need to look any further.
Example: searchWord is "burg". Word 1 "i" does not start with it, word 2 "love" does not, word 3 "eating" does not, but word 4 "burger" does (b-u-r-g match), so we return 4.
If we reach the end of the list without any match, no word has searchWord as a prefix, and we return -1.