Check If a Word Occurs As a Prefix of Any Word in a Sentence - Problem
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.
A prefix of a string s is any leading contiguous substring of s.
Input & Output
Example 1 — Basic Prefix Match
$
Input:
sentence = "i love eating burger", searchWord = "burg"
›
Output:
4
💡 Note:
"burg" is a prefix of "burger" which is the 4th word in the sentence
Example 2 — First Match
$
Input:
sentence = "this problem is an easy problem", searchWord = "pro"
›
Output:
2
💡 Note:
"pro" is a prefix of "problem" which appears at positions 2 and 6, return the first occurrence at index 2
Example 3 — No Match
$
Input:
sentence = "i am tired", searchWord = "you"
›
Output:
-1
💡 Note:
"you" is not a prefix of any word in "i am tired"
Constraints
- 1 ≤ sentence.length ≤ 100
- 1 ≤ searchWord.length ≤ 10
- sentence consists of lowercase letters and spaces
- sentence does not have leading or trailing spaces
- All the words in sentence are separated by a single space
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sentence with words and search prefix
2
Process
Check each word for prefix match
3
Output
Return 1-based index of first match
Key Takeaway
🎯 Key Insight: Split sentence into words and use built-in prefix checking for clean, efficient solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code