Magicsheet logo

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

Easy
97.5%
Updated 6/1/2025

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

What is this problem about?

The "Check If a Word Occurs As a Prefix of Any Word in a Sentence interview question" involves searching for a specific string pattern within a larger text. You are given a sentence (a string of words separated by single spaces) and a searchWord. You need to find the 1-indexed position of the first word in the sentence that starts with searchWord. If no such word exists, return -1.

Why is this asked in interviews?

Companies like Microsoft and Bloomberg use the "Check If a Word Occurs As a Prefix coding problem" to assess basic string parsing and searching skills. It tests whether you can split a sentence into components, handle 1-based indexing, and use language-specific string methods (like startsWith or find) correctly. It’s a core "String interview pattern" task.

Algorithmic pattern used

This problem follows the String Tokenization and Prefix Matching pattern.

  1. Splitting: Split the sentence into an array of individual words based on the space character.
  2. Iteration: Iterate through the resulting array of words using a loop.
  3. Matching: For each word, check if its length is greater than or equal to the length of searchWord and if the beginning of the word matches searchWord.
  4. Indexing: Return the current index plus 1 (to satisfy the 1-indexed requirement) as soon as a match is found.

Example explanation

Sentence: "i love eating burger", searchWord: "burg"

  1. Words: ["i", "love", "eating", "burger"]
  2. index 0 ("i"): No.
  3. index 1 ("love"): No.
  4. index 2 ("eating"): No.
  5. index 3 ("burger"): Yes, "burger" starts with "burg". Result: 4.

Common mistakes candidates make

  • 0-indexing vs 1-indexing: Returning the 0-based array index instead of adding 1.
  • Subsequence vs Prefix: Accidentally checking if the searchWord is anywhere inside the word (like "er" in "burger") instead of specifically at the start.
  • Handling Spaces: Not correctly splitting the sentence if there are multiple spaces (though constraints usually say "single space").

Interview preparation tip

Familiarize yourself with the string manipulation library of your preferred language. Using built-in methods like split() and startsWith() makes your code cleaner and more readable during the interview.

Similar Questions