We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check If a Word Occurs As a Prefix of Any Word in a Sentence

Number: 1566

Difficulty: Easy

Paid? No

Companies: Amazon, Google, Yelp


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.


Code Solutions

# Python solution with line-by-line comments

def is_prefix_of_word(sentence: str, searchWord: str) -> int:
    # Split the sentence into individual words using space as a delimiter.
    words = sentence.split(" ")
    
    # Iterate over the words along with their index (starting at 1).
    for i, word in enumerate(words, start=1):
        # Check if the current word starts with the searchWord.
        if word.startswith(searchWord):
            return i  # Return the 1-indexed position if found.
    
    # If no word starts with the searchWord, return -1.
    return -1

# Example usage:
# print(is_prefix_of_word("i love eating burger", "burg"))  # Should output 4
← Back to All Questions