Given a sentence consisting of a string of words separated by spaces, and a search word, determine if the search word appears as a prefix of any word in the sentence. If it does, return the index (1-indexed) of the first word in the sentence that has the search word as a prefix. If the search word is not a prefix of any word in the sentence, return -1.
Example:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Input: sentence = "i am tired", searchWord = "you"
Output: -1
def isPrefixOfWord(sentence: str, searchWord: str) -> int:
words = sentence.split()
for index, word in enumerate(words):
if word.startswith(searchWord):
return index + 1 # returning 1-indexed position
return -1
# Example Test Cases
print(isPrefixOfWord("i love eating burger", "burg")) # Output: 4
print(isPrefixOfWord("this problem is an easy problem", "pro")) # Output: 2
print(isPrefixOfWord("i am tired", "you")) # Output: -1
Overall time complexity is O(n + k*p), where:
This solution should be efficient for most practical inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?