Sponsored
Sponsored
This method involves splitting the input sentence into words and then iterating through each word to check if the searchWord is a prefix of that word. If a match is found, the index of the word (1-based) is returned. If no match is found, -1 is returned.
Time Complexity: O(n * m)
where n
is the number of words and m
is the average length of words.
Space Complexity: O(1)
.
1function prefixInSentence(sentence, searchWord) {
2 const words = sentence.split(' ');
3 for (let i = 0; i < words.length; i++) {
4 if (words[i].startsWith(searchWord)) {
5 return i + 1;
6 }
7 }
8 return -1;
9}
10
11// Example usage
12const sentence = "i love eating burger";
13const searchWord = "burg";
14console.log(prefixInSentence(sentence, searchWord));
Using split
method to tokenize the sentence. startsWith
checks if the searchWord
is a prefix. Returns a 1-based index if found.
This approach uses a two-pointer technique to traverse the sentence and words simultaneously for efficient prefix checking. It doesn't rely on splitting the string into words but rather navigates the sentence using custom logic.
Time Complexity: O(n)
where n
is the length of the sentence, as it efficiently traverses the string.
Space Complexity: O(1)
as only pointers are used.
A straightforward two-pointer style implementation where i
traverses the sentence and j
tries to match the search_word
. The pointer skips spaces smartly, and converges on a solution quickly.