Search⌘ K
AI Features

Solution: Check If a Word is a Prefix of Any Word in a Sentence

Explore how to use a trie data structure to efficiently check if a given word is a prefix of any word in a sentence. Learn the process of splitting sentences, inserting words with their positions into a trie, and returning the earliest matching word’s index. Understand the time and space complexities involved to solve this prefix search problem with clarity.

Statement

You are given a sentence containing words separated by single spaces and a searchWord. Your task is to determine whether searchWord is a prefix of any word in the sentence.

Return the 1-based index of the first word in which searchWord appears as a prefix.

  • If searchWord is a prefix of multiple words, return the index of the earliest such word.

  • If no word starts with searchWord, return 1-1.

A prefix of a string is any contiguous substring that begins at the first character.

Constraints:

  • 1<=1 <= ...