Check If A Word Occurs As A Prefix Of Any Word In A Sentence
Algorithm/TwoPointers
Intuition
The problem requires finding the position of the first word in a sentence that starts with a given prefix. If such a word is found, the function should return the 1-based index of the word in the sentence. If no word starts with the prefix, it should return -1.
We can approach this problem by:
- Splitting the sentence into individual words.
- Iterating through the words, checking if each word starts with the given prefix.
- Returning the index of the first word that matches the condition.
- If no match is found after checking all words, return -1.
Approach
Below is the step-by-step breakdown of the approach:
-
Split the Sentence:
- The sentence can be split into an array of words using the
split(' ')
method.
- The sentence can be split into an array of words using the
-
Check Each Word:
- Loop through the array of words, checking if each word starts with searchWord using the
startsWith()
method. ThestartsWith()
method is case-sensitive and checks whether the word begins with the specified prefix.
- Loop through the array of words, checking if each word starts with searchWord using the
-
Return the Index:
- If a word matches, return its index (adjusted to be 1-based, so add 1 to the zero-based index). If no match is found, return -1.
Complexity
- Time Complexity: O(n), where n is the number of words in the sentence. This is because we loop through all the words and perform a string comparison for each word.
- Space Complexity: O(m), where m is the length of the sentence, due to the space needed to store the words array after splitting the sentence.