Imagine you're building a smart autocomplete feature for a search engine! Given a sentence containing multiple words separated by spaces and a search term, you need to find if the search term appears as a prefix (beginning) of any word in the sentence.
Your task is to return the 1-indexed position of the first word that starts with the given search term. If no word starts with the search term, return -1.
Key Points:
- A prefix means the search term appears at the very beginning of a word
- Return the position of the first matching word (1-indexed, not 0-indexed)
- If multiple words match, return the smallest index
- Words are separated by single spaces
Example: In sentence "i love eating burger", searching for "burg" should return 4 because "burger" is the 4th word and starts with "burg".
Input & Output
Visualization
Time & Space Complexity
Where n is the number of words and m is the length of the search term. We check each word and compare up to m characters.
Space needed to store the array of words after splitting the sentence
Constraints
- 1 โค sentence.length โค 100
- 1 โค searchWord.length โค 10
- sentence consists of lowercase English letters and spaces
- searchWord consists of lowercase English letters
- Words in sentence are separated by single spaces