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)
.
1def prefix_in_sentence(sentence, search_word):
2 words = sentence.split()
3 for index, word in enumerate(words):
4 if word.startswith(search_word):
5 return index + 1
6 return -1
7
8
9# Example usage
10sentence = "i love eating burger"
11search_word = "burg"
12print(prefix_in_sentence(sentence, search_word))
The split
method breaks the sentence into a list of words. enumerate
provides both a word and its index, and startswith
is used for prefix checking. Returns 1-indexed position.
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.
Implements two-pointer approach by using two nested loops for prefix check: outer loop iterates over words, and inner loop checks the prefix. Maintains an index to track position within sentence.