Problem Description
Given a sentence composed of words separated by a single space and a searchWord, determine if searchWord is a prefix of any word in the sentence. Return the 1-indexed position of the first word where searchWord is a prefix. If searchWord is not a prefix of any word, return -1.
Key Insights
- Split the sentence into individual words using space as the delimiter.
- Iterate over each word and check if the word starts with searchWord.
- Return the index (1-indexed) of the first occurrence where the condition is met.
- If no word meets the condition, return -1.
Space and Time Complexity
Time Complexity: O(n * m) where n is the number of words in the sentence and m is the length of the search word (in the average case, string comparison for prefix check). Space Complexity: O(n) for storing the list of words from the sentence.
Solution
The solution uses a simple string splitting for dividing the sentence into words and then iterates over this list to check if any word starts with the searchWord. We use a straightforward string matching operation (using methods like startsWith or equivalent) to determine if the searchWord is a prefix. The algorithm stops at the first valid match and returns the corresponding 1-indexed position, ensuring minimal work in the best case.